.toggleClass in only 1 element even though there are several with the same class

0

I'm trying to create a multilevel menu but I do not know how to make it just add the class to the element that is inside the <li> that I clicked.

The final idea is to press the arrow I created with JS and add or remove a class in the ul.sub-menu , but only in the ul.submenu that is at the same level as the span of the arrow (this is created as a child of the li that has the class .menu-item-has-children

This is the code:

HTML

<nav class="menu-principal">
      <ul>
        <li class="menu-item-has-children">
          <a href="#">Sobre nosotros</a>
          <ul class="sub-menu">
            <li><a href="#">El equipo</a></li>
            <li class="menu-item-has-children"><a href="#">Nuestras instalaciones</a>
              <ul class="sub-menu">
                <li><a href="#">El equipo</a></li>
                <li><a href="#">Nuestras instalaciones</a></li>
                <li><a href="#">Cómo trabajamos</a></li>
              </ul>
            </li>
            <li><a href="#">Cómo trabajamos</a></li>
          </ul>

        </li>
        <li><a href="#">Vídeos</a></li>
        <li><a href="#">Trabajos</a></li>
        <li><a href="#">Blog</a></li>
        <li><a href="#">Contacto</a></li>
        <li class="menu-item-has-children"><a href="#">Pide presupuesto</a>
          <ul class="sub-menu">
            <li><a href="#">El equipo</a></li>
            <li><a href="#">Nuestras instalaciones</a></li>
            <li><a href="#">Cómo trabajamos</a></li>
          </ul>
        </li>
      </ul>  
  </nav>

JS

// CREAR ELEMENTO PARA ABRIR MENU EN MOVIL (FLECHA)
  $(".menu-item-has-children > a").append('<span class="btn-mostrar"><i class="fas fa-angle-down"></i></span>');

 // ABRIR SUBMENU AL HACER CLICK EN FLECHA
    $(".btn-mostrar").click(function(){
        $(".sub-menu").toggleClass("mostrar");
    });

});
    
asked by Pablo 18.09.2018 в 17:45
source

2 answers

1

Try using jQuery's .next() like this:

$(".btn-mostrar").click(function(){
    $(this).parent().next(".sub-menu").toggleClass("mostrar");
});
    
answered by 18.09.2018 в 18:04
0

In programming, there is the concept of this that in the case of events (which is what concerns us) refers to the element that triggered it. In such a way that the this in the case of an event of the type click , refers to the element that was clicked with the mouse.

Based on this principle, we can only show the .sub-menu brother of the element that we do click , which in your case is the .btn-mostrar :

$(".btn-mostrar").click(function(){
    $(this).siblings('.sub-menu').toggleClass("mostrar");
});

With that, you should already apply the class show only to the corresponding submenu.

    
answered by 18.09.2018 в 18:06