luqita
luqita

Reputation: 4077

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'); ???

Upvotes: 6

Views: 10600

Answers (3)

micadelli
micadelli

Reputation: 2482

For better performance than eq, you could use slice:

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

Upvotes: 0

rodneyrehm
rodneyrehm

Reputation: 13557

jQuery#closest() will return the current element, if it matches the selector. So you can either use jQuery#parents() like suggested by @Frederic, or manually go up one element:

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

That said, you had another problem in your code. You wrapped the two closest() calls in parentheses. This would have the effect of those two calls being evaluated before the others. Since you probably don't have a function called closest in your scope, the given code would've failed with a ReferenceError.

(I'm only providing this as an explanation to why your initial code failed, you should really go with @Frederic's suggestion)

Upvotes: 2

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

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.

Upvotes: 16

Related Questions