JQuery: finding the second closest div

How to find the second closest div?

For example, to get the closest, I successfully use:

var closest_div_id = $(this).closest('div').attr('id');

Now, how do I get the second nearest? Sort of:

$(this).(closest('div').closest('div')).attr('id'); ???
+5
source share
3 answers

Assuming it is thisnot an element <div>, you can pass the parents () selector and write:

var secondClosestId = $(this).parents("div").eq(1).attr("id");

parents()returns ancestors ordered from closest to external, so eq()you can use it here. See this question for a general case.

+12
source

jQuery # () , . , jQuery # parents(), @Frederic, :

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

, . () . , . , , , , ReferenceError.

( , , @Frederic)

+2

For better performance than eq, you can use slice:

var secondClosest = $(this).parents("div").slice(1, 2).attr('id');
0
source

All Articles