How to find nth parent of an element using jquery

Rakhitha Nimesh picture Rakhitha Nimesh · Nov 18, 2011 · Viewed 35.5k times · Source

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

Answer

Richard Dalton picture Richard Dalton · Nov 18, 2011

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

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

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