Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we write this in javascript $(this).parent('p')

How do i write this selector in plain javascript

$(this).parent('p')
like image 648
Pinkie Avatar asked Dec 07 '25 08:12

Pinkie


1 Answers

Since the jQuery .parent(selector) function only checks the immediate parent, you can create a function like this:

function getParent(o, tag) {
    if (o.parentNode.tagName.toLowerCase() == tag.toLowerCase()) {
        return(o.parentNode);
    } else {
        return(null);
    }
}

Then, you can just call this:

getParent(this, 'p');

Or, if you want it to return an array similar to how jQuery does it, you would use this:

function getParent(o, tag) {
    var results = [];
    if (o.parentNode.tagName.toLowerCase() == tag.toLowerCase()) {
        results.push(o.parentNode);
    }
    return(results);
}

Then, you can just call this (and get an array back):

getParent(this, 'p');

If you wanted the equivalent of the jQuery .parents(selector) function that returns all ancestors that match a tag type, you would use this:

function getParents(o, tag) {
    var results = [];
    while ((o = o.parentNode) && o.tagName) {
        if (o.tagName.toLowerCase() == tag.toLowerCase()) {
            results.push(o);
        }
    }
    return(results);
}

And, you would call it like this:

getParents(this, 'p');
like image 115
jfriend00 Avatar answered Dec 08 '25 21:12

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!