uksz uksz - 7 months ago 69
HTML Question

How to toggle hide/show closest UL in HTML using jQuery?

I have been using this example to build the tree for my object. As you can see, it bases on the model of nested

ul
which builds the tree:

<ul class="tree">
<li>
Animals
<ul>
<li>Birds</li>
<li>
Mammals
<ul>
<li>Elephant</li>
<li>Mouse</li>
</ul>
</li>
<li>Reptiles</li>
</ul>
</li>


I've been trying to add functionality to collapse the tree. For example, if I click on
Mammals
, it hides
Elephant
and
Mouse
, only within the class 'tree'.

I tried using this:

$('li').on('click', function() {
$(this).closest('ul').nextAll('.hidden:first').toggle();
});


and added hidden class as display none, however, it seems that the function is not toggled when I click on any
li
.

What am I doing wrong?

Answer

You need this,

$('li').on('click', function(e) {
  e.stopPropagation();
  $(this).find('ul').slideToggle();
});

Fiddle

Find the child elements by using .find() method.

Then use slideToggle() toggling with a animation effect

Note: you need to use event.stopPropagation() to prevent the event to propagate to the parent lis