How do I get the n-th level parent of an element in jQuery?

JavascriptJqueryParent

Javascript Problem Overview


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 this?

Javascript Solutions


Solution 1 - Javascript

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".

Solution 2 - Javascript

Depends on your needs, if you know what parent your looking for you can use the .parents() selector.

E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/

<div id="One">
    <div id="Two">
        <div id="Three">
            <div id="Four">
    
            </div>
        </div>
    </div>
</div>


var top = $("#Four").parents("#One");

alert($(top).html());

Example using index:

//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);

alert($(topTwo ).html());

Solution 3 - Javascript

You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")

Solution 4 - Javascript

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

Solution 5 - Javascript

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'

Solution 6 - Javascript

It's simple. Just use

$(selector).parents().eq(0); 

where 0 is the parent level (0 is parent, 1 is parent's parent etc)

Solution 7 - Javascript

Just add :eq() selector like this:

$("#element").parents(":eq(2)")

You just specify index which parent: 0 for immediate parent, 1 for grand-parent, ...

Solution 8 - Javascript

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

Solution 9 - Javascript

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).

Solution 10 - Javascript

you can also use :

$(this).ancestors().eq(n) 

ex: $(this).ancestors().eq(2) -> the parent of the parent of this.

Solution 11 - Javascript

As parents() returns a list, this also works

$('#element').parents()[3];

Solution 12 - Javascript

You could use something like this:

(function($) {
    $.fn.parentNth = function(n) {
        var el = $(this);
        for(var i = 0; i < n; i++)
            el = el.parent();
        
        return el;
    };
})(jQuery);

alert($("#foo").parentNth(2).attr("id"));

http://jsfiddle.net/Xeon06/AsNUu/

Solution 13 - Javascript

using eq appears to grab the dynamic DOM whereas using .parent().parent() appears to grab the DOM that was initially loaded (if that is even possible).

I use them both on an element that has classes applied it to on onmouseover. eq shows the classes while .parent().parent() doesnt.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArtur KeyanView Question on Stackoverflow
Solution 1 - JavascriptFrédéric HamidiView Answer on Stackoverflow
Solution 2 - JavascriptHenryView Answer on Stackoverflow
Solution 3 - JavascriptJoseph MarikleView Answer on Stackoverflow
Solution 4 - Javascripta'rView Answer on Stackoverflow
Solution 5 - JavascriptDaneView Answer on Stackoverflow
Solution 6 - JavascriptzatatatataView Answer on Stackoverflow
Solution 7 - JavascriptMBOView Answer on Stackoverflow
Solution 8 - JavascriptzzzzBovView Answer on Stackoverflow
Solution 9 - Javascriptashishyadaveee11View Answer on Stackoverflow
Solution 10 - JavascriptMouna CheikhnaView Answer on Stackoverflow
Solution 11 - JavascriptDidThisView Answer on Stackoverflow
Solution 12 - JavascriptAlex TurpinView Answer on Stackoverflow
Solution 13 - Javascriptuser875234View Answer on Stackoverflow