How do i write this selector in plain javascript
$(this).parent('p')
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With