Home > Enterprise >  How to call the slideToggle() function on the nearest element
How to call the slideToggle() function on the nearest element

Time:01-07

I have a menu and in some li there are sub-menu, and there are 3 such nestings. I need that when clicking on the li, which contains the ul with the "sub-menu" class, the slideToggle () function works on the nearest sub-menu. I tried through closest() but didn't work. How can i do this?

$(".menu-item-has-children").click(function(event) {
  event.preventDefault();
  $(this).closest(".sub-menu").slideToggle();
});

Menu structure

CodePudding user response:

closest() goes up the DOM tree. The ul elements that you're trying to target are children of the li that's clicked, so you need to use children() instead:

$(".menu-item-has-children").click(e => {
  e.preventDefault();
  $(e.target).children(".sub-menu").slideToggle();
});
  • Related