javascriptjqueryparent-childchildrentoggleclass

jquery toggleClass to just children element


i have an issue to toggleclass for just children element.

<ul class="sample-menu">
<li id="sample-topmenu_2">
    <a href="#" class="sample-icon">Menu Text</a>
    <ul class="sample-submenu">
        <li class="submenu"><a href="#" class="sample-icon">Submenu Text</a></li>
        <li class="submenu"><a href="#" class="sample-icon">Submenu Text</a></li>
    </ul>
</li>
<li id="sample-topmenu_3">
    <a href="#" class="sample-icon">Menu Text2</a>
    <ul class="sample-submenu">
        <li class="submenu"><a href="#" class="sample-icon">Submenu Text2</a></li>
        <li class="submenu"><a href="#" class="sample-icon">Submenu Text2</a></li>
    </ul>
</li>

i use this jquery toggle, but it's toggle all li elements for all menu.

$( "*[id^=bga-topmenu_] p" ).click(function() {
  $("li.submenu").toggleClass( "sumenu_show" );
});

I appreciate your help.


Solution

  • Try:

    $( "*[id^=bga-topmenu_]" ).click(function() {
      $(this).find("li.submenu").toggleClass( "sumenu_show" );
    });
    

    You can use $(this) to get the current context (i.e. the clicked element) and then find all <li> elements with the submenu class within that context, using the .find() method.