Show / hide each element within a class with toggle (jquery)

3

I have a class .menu-departamento and inside it I have a h3 and a ul li , in which I'm putting a toogle effect.

In the code below when I click on a h3 it displays all ul and you want it to display only the ul that is just below h3 clicked.

Follow the example below:

<div class="menu-departamento">
    <h3>
        cartuchos e toners  
    </h3>
    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>

    <h3>impressoras</h3>
    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>

    <h3>Cadernos</h3>

    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>

    <h3>acessórios</h3>
    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>
</div>

<script>
$(document).ready(function(){
    $('.menu-departamento > ul > li').hide();

    $('.menu-departamento h3').click(function() {
        $('.menu-departamento > ul > li').toggle('slow, 1000');
    });

});
</script>

Sample reference in jsfiddle: link

    
asked by anonymous 19.01.2015 / 14:00

2 answers

4

You can use the next () function to select the next element.

In your example, I modified the line $('.menu-departamento > ul > li').hide(); to hide all ul . Then next() always selects the next ul , since in your code there is always a ul after a h3 .

$(document).ready(function() {
  $('.menu-departamento > ul').hide();
  
  $('.menu-departamento h3').click(function() {
    $(this).next().toggle('slow, 1000');
  });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="menu-departamento">
  <h3>cartuchos e toners</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
  <h3>impressoras</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
  <h3>Cadernos</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
  <h3>acessórios</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
</div>
    
19.01.2015 / 14:09
3

Use a container between each listing. See how you got on JSFiddle .

    
19.01.2015 / 14:08