Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

parent

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?

like image 546
matt Avatar asked May 03 '13 14:05

matt


3 Answers

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

like image 77
Adil Avatar answered Sep 23 '22 17:09

Adil


Use .eq() and .parents() like this:

$(this).parents().eq(2).attr("id");
like image 39
97ldave Avatar answered Sep 21 '22 17:09

97ldave


you can also try.

$(this).parents(':eq(2)');  //and then get ID
like image 7
Suresh Atta Avatar answered Sep 23 '22 17:09

Suresh Atta