Arjun
Arjun

Reputation: 6729

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.

Upvotes: 10

Views: 11488

Answers (4)

Ashraful Islam
Ashraful Islam

Reputation: 47

I'm using this code to add active class depending on the page. This is working 100% for multi level sub-menus of AdminLTE 3, just put this code in the footer section of your page.

var url = window.location;
const allLinks = document.querySelectorAll('.nav-item a');
const currentLink = [...allLinks].filter(e => {
    return e.href == url;
});

currentLink[0].classList.add("active");
currentLink[0].closest(".nav-treeview").style.display = "block ";
currentLink[0].closest("ul.nav-treeview").closest('li').classList.add('menu-open');

$('.menu-open').find('a').each(function() {
    if (!$(this).parents().hasClass('active')) {        
        $(this).parents().addClass("active");
        $(this).addClass("active");
    }
});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074435

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.

Upvotes: 21

vim
vim

Reputation: 1118

you can use

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

Upvotes: 1

Oliver M Grech
Oliver M Grech

Reputation: 3171

following my previous comment.. here's the example promised... :)

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
  });

Stop at the second index

Further info can be found here

http://api.jquery.com/each/

Upvotes: 0

Related Questions