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();
});
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();
});