Is there a better way to get the parent of the parent of the parent... like 5 times?
So Instead of using this:
$(this).parent().parent().parent().parent().parent()
I could use something like this:
$(this).goBacktoNthParent(5);
Is it possible?
:eq()
selectorThe :eq()
selector allows you to target the element at the zero-based index of the set that was matched...
$(this).parents(':eq(4)')
Note: use parent(s) selector
Because the selector is zero based, we gave it one less than the number targeted.
DEMO: http://jsfiddle.net/pmMFv/
.eq()
methodThe .eq()
method is effectively the same as its selector counterpart, allowing you to target the element at the zero-based index of the set that was matched...
$(this).parents().eq(4)
Note: use parent(s) selector
DEMO: http://jsfiddle.net/pmMFv/2/
parentNode
in a loopFor greatest performance, we could use the .parentNode
property of the element, and run it in a loop, updating a variable with the newest parent each time...
var el = this, i = 5;
while(i-- && (el = el.parentNode));
$(el)
DEMO: http://jsfiddle.net/pmMFv/1/
You can easily create your own function:
function getNthParentOf(elem,i) {
while(i>0) {
elem = elem.parent();
i--;
}
return elem;
}
var something = getNthParentOf($(this),5);
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