Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call the slideToggle() function on the nearest element

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading