Home > Net >  jQuery toggle class on sub element of li - not working
jQuery toggle class on sub element of li - not working

Time:09-29

So I have multiple LI's like below as it's a menu and I am trying to create a drop-down but for some reason, my jQuery code is not working. Can someone help me?

FYI I can't change HTML as it's dynamically generating in Shopify. I can only change jQuery and CSS

<li >
    <a >Furry Artist</a>
    
    <ul >
        
        <li >
            <a href="/collections/erdbeer-joghurt" >Erdbeer Joghurt</a>
            
        </li>
        
        <li >
            <a href="/collections/jeson-rc" >Jeson RC</a>
            
        </li>
        
    </ul>
    
</li>
$( document ).ready(function() {
$("ul.subLinks").addClass("inactive");
});

$('a.site-nav.lvl-1').click(function() {
  $(this).find("ul.subLinks").toggleClass('active-drop-down');
});
.inactive {
  display:none;
}

.active-drop-down {
  display:block !important;
}

CodePudding user response:

Your issue is $(this).find... in the a click handler - at this point, this is the a.

.find() looks at the selectors children - but the menu is not a child of the a, it's a sibling.

Change to

$(this).closest("li").find("ul.subLinks"...

(maybe $(this).next().toggleClass... with a caveat on .this() that it's always the very next element).

Updated snippet:

$('a.site-nav.lvl-1').click(function() {
  $(this).closest("li").find("ul.subLinks").toggleClass('active-drop-down');
});
.inactive {
  display:none;
}

.active-drop-down {
  display:block !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>
  <li >
    <a >Furry Artist</a>
    <ul >
      <li >
        <a href="/collections/erdbeer-joghurt" >Erdbeer Joghurt</a>
      </li>
      <li >
        <a href="/collections/jeson-rc" >Jeson RC</a>
      </li>
    </ul>
  </li>
</ol>

  • Related