Search code examples
jqueryjquery-selectorsshow-hide

jquery show/hide next ul


I have a problem with show/hide ul element in this sample. my jquery script work on any element except ul elemeny

$('.dropdown-toggle').on('click', function(event) {
  $(this).next('ul').hide();
});
<a href="#" class="dropdown-toggle">
  <span class="menu-text"> Link </span>
</a>

<b class="arrow"></b>
<ul class="submenu nav-show" style="display:block">
  <li class="">1</li>
  <li class="">3</li>
  <li class="">4</li>
</ul>

http://jsfiddle.net/c8kouunk/1/


Solution

  • That is because next will only target the immediate next sibling, which is b tag in your case.

    You need to target the first element from nextAll ul siblings:

    $('.dropdown-toggle').on('click', function(event) {
     $(this).nextAll('ul:first').hide();
    });
    

    Working Demo

    If you want to toggle the ul element then use .toggle() instead of .hide() above:

    $(this).nextAll('ul:first').toggle();
    

    Demo with toggle effect