Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Finding second closest div

How can I find the second closest div?

For example, to get the closest one, I am successfully using:

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

Now, how do I get the second closest? Something like:

$(this).(closest('div').closest('div')).attr('id'); ???
like image 527
luqita Avatar asked Jul 10 '12 19:07

luqita


1 Answers

Assuming this is not a <div> element, you can pass a selector to parents() and write:

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

parents() returns the ancestors ordered from the closest to the outer ones, so eq() can be used here. See this question for the general case.

like image 199
Frédéric Hamidi Avatar answered Oct 13 '22 12:10

Frédéric Hamidi