6

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'); ???
luqita
  • 4,008
  • 13
  • 60
  • 93

3 Answers3

15

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.

Community
  • 1
  • 1
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
2

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)

rodneyrehm
  • 13,442
  • 1
  • 40
  • 56
  • I think you need to either remove one of the `.closest('div')` or remove `.parent()`, otherwise you are going to the 3rd closest parent. However, if the `.parent()` isn't the target div, it won't result in the same as using `.closest('div').closest('div')` – Kevin B Jul 10 '12 at 19:53
  • 2
    well, no. please read the docs on closest() I provided in my answer and see »Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.« – rodneyrehm Jul 10 '12 at 19:55
0

For better performance than eq, you could use slice:

var secondClosest = $(this).parents("div").slice(1, 2).attr('id');
micadelli
  • 2,482
  • 6
  • 26
  • 38