How to find nth parent of an element using jquery

JqueryDomNavigationParent

Jquery Problem Overview


I want to find the nth parent element of an given element and access the attributes of parent.

<div id='parent1'><br/>
  <div id='parent2'><br/>
       <span><p id='element1'>Test</p></span><br/>
  </div><br/>
  <div id='parent3'><br/>
       <span><p id='element2'>Test</p></span><br/>
  </div><br/>
</div>

I want to access the 3rd parent element of element1 without using

$('#element1').parent().parent().parent()

Any help would be appreciated

Jquery Solutions


Solution 1 - Jquery

You can use .parents() and .eq():

$('#element1').parents().eq(2);

http://jsfiddle.net/infernalbadger/4YmYt/

Solution 2 - Jquery

parents() returns a list, so this works:

$('#element1').parents()[2];

Solution 3 - Jquery

use:

$('#element1').closest('#parent1');

Solution 4 - Jquery

You could make a little plugin to take care of that:

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

and then use it as:

$('#element1').nthParent(3);

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
QuestionRakhitha NimeshView Question on Stackoverflow
Solution 1 - JqueryRichard DaltonView Answer on Stackoverflow
Solution 2 - JqueryDidThisView Answer on Stackoverflow
Solution 3 - JqueryAlexView Answer on Stackoverflow
Solution 4 - Jquerygion_13View Answer on Stackoverflow