Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 247
Arjun Avatar asked Mar 02 '11 10:03

Arjun


People also ask

What is closest method in jQuery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

How do I find a specific parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

How do you select all ancestors of an element?

To select all ancestor elements of an element, the parents() method is used. This method is used to find all the parent elements related to the selected element. This method traverse all the levels up the selected element and return that all elements.


1 Answers

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.

like image 163
T.J. Crowder Avatar answered Oct 07 '22 00:10

T.J. Crowder