Hide and Show all li decendentes of a ul - Jquery

Asked

Viewed 1,339 times

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 didn’t work...

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

I wish I could, once I click on the corresponding H4 hide and show the list as in a toggle, how should I proceed?

2 answers

4


Each ul is brother (sibling) of h4 clicked, and occurs immediately after it. To select it then, one can use next, and then proceed to search for their descendants:

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

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

$("h4").click(function() {
    $(this).nextAll("ul:eq(0)").find("li").toggle();
});
  • Next is good option here. +1

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: http://jsfiddle.net/Sergio_fiddle/rczL9h0n/

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

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

  • I’m on my cell phone now and I can’t test it, but Voce tried it with . Closest('ul') ?

  • 3

    @Jader closest search in the ancestors of the element, and not in the brothers.

  • 1

    @mgibsonbr indeed, the actual function does not match the literal translation... my fault!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.