Toggle the display of the ul submenu only if the parent element li is clicked

I looked at some other questions on this site that I thought might help, like this and this , but they don't seem to answer my question. I have the following:

$(document).ready(function() { $(".has-submenu ul").hide(); $(".has-submenu").click(function() { $(this).children("ul").toggle(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#">Item 1</a></li> <li class="has-submenu"><a href="#">Item 2</a> <ul> <li><a href="#">Sub Item 1</a></li> </ul> </li> </ul> 

As you can see from this snippet, the submenu is hidden regardless of whether I click "item 2" or "subparagraph 1". I understand that this is because "Sub Item 1" is part of <li class="has-submenu"> , so once he clicked, he goes through and switches the submenu. CSS does what it should do, I just donโ€™t know how to configure CSS to say "Hide the submenu if the parent li was pressed. I tried modifying the jQuery click function to search for $(".has-submenu a") to indicate that he should do this only when this particular item is clicked, but this does not seem to help.

I am sure this is a simple solution, I just donโ€™t know how to do it. Thanks!

+7
jquery css
source share
3 answers

You can use $(".has-submenu > a") to select a , which is a direct child of .has-submenu , and then use next() to target ul

 $(".has-submenu ul").hide(); $(".has-submenu > a").click(function() { $(this).next("ul").toggle(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#">Item 1</a></li> <li class="has-submenu"><a href="#">Item 2</a> <ul> <li><a href="#">Sub Item 1</a></li> </ul> </li> </ul> 
+3
source share

You must change the selector to $(".has-submenu>a") and switch its .siblings("ul") to click.

 $(document).ready(function() { $(".has-submenu ul").hide(); $(".has-submenu>a").click(function() { $(this).siblings("ul").toggle(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#">Item 1</a></li> <li class="has-submenu"><a href="#">Item 2</a> <ul> <li><a href="#">Sub Item 1</a></li> </ul> </li> </ul> 
+1
source share

This works even if .has-submenu has more than one element.

 $(".has-submenu ul").hide(); $(".has-submenu > a").click(function() { $(this).parent().find('ul').each(function(){$(this).toggle();}); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><a href="#">Item 1</a></li> <li class="has-submenu"><a href="#">Item 2</a> <ul> <li><a href="#">Sub Item 1</a></li> </ul> <ul> <li><a href="#">Sub Item 2</a></li> </ul> </li> </ul> 
0
source share

All Articles