Hide and Show all the descendents of an ul - JQuery

4

I have the following lists:

<h4>Procedures</h4>
<ul>
  <li">Foo</li>
  <li">Foobar</li>
  <li">FooBarBazz</li>
</ul>

<h4>Packages</h4>
<ul>
  <li">Foo</li>
  <li">Foobar</li>
  <li">FooBarBazz</li>
</ul>

I tried with this JQuery, but it did not work ...

<script> 
$(document).ready(function(){
   $('h4').click(function(){
     this>li.toggle();
   });
});
</script>

I wanted to be able to, as soon as I clicked on the corresponding H4 hide and show list as in a toggle, how should I proceed?

    
asked by anonymous 07.08.2014 / 21:13

2 answers

4

Each ul is sibling ) of h4 clicked, and occurs immediately after it. To select it then you can use next , and then proceed to search your descendants:

$("h4").click(function() {
    $(this).next().find("li").toggle();
});

If it is only close but not immediately next, another option would be to use nextAll and fetch the first ul found:

$("h4").click(function() {
    $(this).nextAll("ul:eq(0)").find("li").toggle();
});
    
07.08.2014 / 21:25
3

Test like this:

<script> 
$(document).ready(function(){
    $('h4').each(function(index){
          $(this).click(function(){
              $(this).parent().find('ul').eq(index).find('li').toggle();
           });
    });
});
</script>

Example: link

The difficulty here is that all <h4> has the same parent, so you have to save the index of each and call .eq () to select the ul element.

You can also use .toggleClass () and do the same with a CSS class.

    
07.08.2014 / 21:15