jQuery: parent() times 3 - how to avoid stacking of parents if I don't know a selector

matt picture matt · May 3, 2013 · Viewed 7.9k times · Source

I couldn't find a quick answer to this problem …

I'm inside a click-event and using $(this)

I'm trying to select an element three levels up without knowing what selector it has.

$(this).parent().parent().parent().attr('id')

This works fine, but is there a better way in doing this?

Like parent(3x) or similar?

Answer

Adil picture Adil · May 3, 2013

You can try using eq() with parents(). eq() is zero base index so first element will have zero index and third element will have 2 index.

$(this).parents().eq(2).attr('id');

This is equal to:

$(this).parent().parent().parent().attr('id');

The .parents() method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up; the elements are returned in order from the closest parent to the outer ones, Reference