When I want to get, for example, the 3rd level parent of the element I must write $(\'#element\').parent().parent().parent()
Is there a more optimal method for
Just add :eq()
selector like this:
$("#element").parents(":eq(2)")
You just specify index which parent: 0 for immediate parent, 1 for grand-parent, ...
Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():
$('#element').parents().eq(0); // "Father".
$('#element').parents().eq(2); // "Great-grandfather".
A faster way is to use javascript directly, eg.
var parent = $(innerdiv.get(0).parentNode.parentNode.parentNode);
This runs significantly faster on my browser than chaining jQuery .parent()
calls.
See: http://jsperf.com/jquery-get-3rd-level-parent
If you plan on reusing this functionality, the optimal solution is to make a jQuery plugin:
(function($){
$.fn.nthParent = function(n){
var $p = $(this);
while ( n-- >= 0 )
{
$p = $p.parent();
}
return $p;
};
}(jQuery));
Of course, you may want to extend it to allow for an optional selector and other such things.
One note: this uses a 0
based index for parents, so nthParent(0)
is the same as calling parent()
. If you'd rather have 1
based indexing, use n-- > 0
If you have a common parent div you can use parentsUntil() link
eg: $('#element').parentsUntil('.commonClass')
Advantage is that you need not to remember how many generation are there between this element and the common parent(defined by commonclass).
Didn't find any answer using closest()
and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:
You can use the closest()
function combined with selectors to get the first element that matches when traversing upwards from the element:
('#element').closest('div') // returns the innermost 'div' in its parents
('#element').closest('.container') // returns innermost element with 'container' class among parents
('#element').closest('#foo') // returns the closest parent with id 'foo'