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?
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?
Share Improve this question asked Feb 5, 2012 at 15:01 AlonAlon 7,75820 gold badges63 silver badges100 bronze badges 1- 1 Can you please post your HTML structure. – Rory McCrossan Commented Feb 5, 2012 at 15:03
6 Answers
Reset to default 11Using the :eq()
selector
The :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/pmMFv/
Using the .eq()
method
The .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/pmMFv/2/
Using parentNode
in a loop
For 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/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 there are identifying markers on the parent element you want to get - such as an id
or class
you can use $(this).closest("#grandparentElement")
You can use the .parents traversing function in conjunction with the :nth()
selector.
So the result will be something like:
$(this).parents(':nth(5)'));
Notice: the :nth()
index starts from 0 so for your case it should be:
$(this).parents(':nth(4)'));
Hope, this would be of any help.
try using .parentsUntil()
working example: http://jsfiddle/ylokesh/wLhcA/
Well you can try
var parentControl = $('#yourcontrol').parent();
var grandParent = parentControl.parent();