Artur Keyan Artur Keyan -4 years ago 184
Javascript Question

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

Is there a more optimal method for this?

Answer Source

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".
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download