开发者

How to find the 2nd closest ancestor in jQuery?

开发者 https://www.devze.com 2023-02-14 20:15 出处:网络
My DOM looks something like this: <li> <li><a class=\"editEntity>Edit</a></li>

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开发者_C百科() {
    $(this).closest('li').closest('li').addClass('selected');
});

Any help is appreciated.


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.


you can use

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


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/


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");
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号