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

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?

This question is related to javascript jquery parent

The answer is


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.


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


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


It's simple. Just use

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

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


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'

As parents() returns a list, this also works

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

you can also use :

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

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


Just add :eq() selector like this:

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

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


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


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/


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());

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to parent

parent & child with position fixed, parent overflow:hidden bug How can I return to a parent activity correctly? How to call a parent method from child class in javascript? Make div (height) occupy parent remaining height jQuery: get parent tr for selected radio button Select parent element of known element in Selenium fork() child and parent processes How do I get the n-th level parent of an element in jQuery? How to delete parent element using jQuery PHP Accessing Parent Class Variable