Hiding menu brother

Asked

Viewed 49 times

-1

I have a main menu that is on li H3 and the submenus are in li H4. In the structure, they are like brothers. Within the same ul and in the same li. When I click on the menu li H3 I want the menu li H4 disappear. I did it with Jquery:

$('.itemSubmenuMobile ul li h3').click(function(event) {
  event.preventDefault();
  $('.itemSubmenuMobile ul li h4').toggle(300);
});

The item li H4 is disappearing correctly. But the li which is above H4 still remains. In this case, add only the content and the space of the li. How I would make to disappear li also?

<ul style="overflow: hidden; display: block;">
  <li>
    <h3>
      <a href="/produtos/papeis-de-parede-1">Item 1</a>
    </h3>
  </li>
  <li>
    <h4><a href="/produtos/decorativo-8">Subitem 1</a></h4>
  </li>
  <li>
    <h4><a href="/produtos/rustico-7">Subitem 2</a></h4>
  </li>
<li>
    <h3>
      <a href="/produtos/papeis-de-parede-1">Item 1</a>
    </h3>
  </li>
  <li>
    <h4><a href="/produtos/decorativo-8">Subitem 1</a></h4>
  </li>
  <li>
    <h4><a href="/produtos/rustico-7">Subitem 2</a></h4>
  </li>
</ul>

  • You want both of them h4 be closed?

  • Changing the HTML was more logical. This is possible?

  • @Sergio HTML can’t change. Yes, I want you to close H4.

1 answer

1


You can use the .closest('li').nextAll('li') to pick up the next li. Then make a .each and stops it if one of the descendants of the li for a h3.

$('ul li h3').click(function(event) {
  event.preventDefault();
  $(this).closest('li').nextAll('li').each(function() {
    if (this.firstElementChild.matches('h3')) return false;
    $(this).toggle(300);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul style="overflow: hidden; display: block;">
  <li>
    <h3>
      <a href="/produtos/papeis-de-parede-1">Item 1</a>
    </h3>
  </li>
  <li>
    <h4><a href="/produtos/decorativo-8">Subitem 1</a></h4>
  </li>
  <li>
    <h4><a href="/produtos/rustico-7">Subitem 2</a></h4>
  </li>
  <li>
    <h3>
      <a href="/produtos/papeis-de-parede-1">Item 2</a>
    </h3>
  </li>
  <li>
    <h4><a href="/produtos/decorativo-8">Subitem 1</a></h4>
  </li>
  <li>
    <h4><a href="/produtos/rustico-7">Subitem 2</a></h4>
  </li>
</ul>

Browser other questions tagged

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