Skip to content
Advertisement

How to find the 2nd closest ancestor in jQuery?

My DOM looks something like this:

<li>
   <li><a class="editEntity>Edit</a></li>
   <li><a class="deleteEntity>Delete</a></li>
</li>

When the used clicks on ‘Edit’, I want to change the outer <li> to <li class="selected>.

I tried something like this, but this is not working:

$('li a.editEntity').live('click', function() {
    $(this).closest('li').closest('li').addClass('selected');
});

Any help is appreciated.

Advertisement

Answer

Go up a parent:

$(this).closest('li').parent().closest('li').addClass('selected');

It wasn’t working because closest starts with the current element, and so if you call it on something that matches the selector, you get back the same thing you started with.

Live example

Or you can use parents with the :eq selector:

$(this).parents("li:eq(1)").toggleClass("selected");

Note that :eq uses 0-based indexes, so :eq(1) is the second parent li.

Live example

Your quoted HTML is invalid, though (an li can’t directly contain an li); I assume you meant:

<li>
   <ul>
      <li><a class="editEntity>Edit</a></li>
      <li><a class="deleteEntity>Delete</a></li>
   </ul>
</li>

…or similar.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement