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

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


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


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#Onevar topTwo = $("#Four").parents().eq(2);alert($(topTwo ).html());


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