51

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

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
Rakhitha Nimesh
  • 1,393
  • 2
  • 16
  • 26
  • 1
    Possible duplicate of [How do I get the n-th level parent of an element in jQuery?](http://stackoverflow.com/questions/7093659/how-do-i-get-the-n-th-level-parent-of-an-element-in-jquery) – Frédéric Hamidi Nov 18 '11 at 09:41

4 Answers4

80

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

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

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

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
8

parents() returns a list, so this works:

$('#element1').parents()[2];
DidThis
  • 491
  • 6
  • 5
8

use:

$('#element1').closest('#parent1');
Alex
  • 1,630
  • 1
  • 20
  • 31
6

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);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
gion_13
  • 41,171
  • 10
  • 96
  • 108