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

Artur Keyan picture Artur Keyan · Aug 17, 2011 · Viewed 111.3k times · Source

When I want to get, for example, the 3rd level parent of the element I must write $('#element').parent().parent().parent() Is there a more optimal method for this?

Answer

Frédéric Hamidi picture Frédéric Hamidi · Aug 17, 2011

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