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'); ???
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With