Skip to content
Advertisement

Target a child link in a nav menu

I’m creating a dropdown nav for mobile and I’m using an active class to hide and show submenus via CSS. The code below works for the initial list item, but closes the parent as soon I try and open a child list item in the submenu (which uses the same structure and classes)

What I think is happening

I think the issue is that as soon as I click inside the parent li the js registers the click event and closes via the toggle.

Problem

So how do I get the javascript to select the child link and attach the click event to that, but still add the active class to the parent li item so the CSS cascades through the submenus?

HTML:

<ul>
<li class="menu-item-has-children nav-level-0">
    <a class="#">Child link</a>
    <ul class="submenu"></ul>
</li>
<li class="menu-item-has-children nav-level-0">
    <a class="#">Child link</a>
    <ul class="submenu"></ul>
</li>
</ul>

Javascript:

var nav_link = document.querySelectorAll(".menu-item-has-children");

for (var i = 0; i < nav_link.length; i++) {
  nav_link[i].addEventListener("click", function() {
    this.classList.toggle('active');
  });
}

Advertisement

Answer

So how do I get the javascript to select the child link and attach the click event to that, but still add the active class to the parent li item so the CSS cascades through the submenus?

Try this

var nav_link = document.querySelectorAll(".menu-item-has-children");

for (var i = 0; i < nav_link.length; i++) {
  nav_link[i].querySelector('a').addEventListener("click", function () {
    this.parentElement.classList.toggle('active');
  });
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement