I have a simple Javascript-enabled Wordpress menu plugin that I've built myself.
It has a top level menu that works fine and a sub-menu dropdown that doesn't. For some reason, only the first (top) submenu dropdown onclick function works as expected - the rest don't work at all. It seems like it's a CSS targeting issue, but I don't see how it can be, when I look at the code.
As I say, the code works as expected on the first li -just not the rest.
I'd love to know what I've done wrong
The JS is as follows:
const hamburger = document.querySelector(".hamburger");
const navMenu = document.querySelector(".nav-menu");
hamburger.addEventListener("click", mobileMenu);
function mobileMenu() {
hamburger.classList.toggle("active");
navMenu.classList.toggle("active");
}
const triangle = document.querySelector(".menu-hide-me");
const subMenu = document.querySelector(".sub-menu");
triangle.addEventListener("click", giveclasstosubmenu);
function giveclasstosubmenu() {
triangle.classList.toggle("sub-open");
subMenu.classList.toggle("sub-open");
}
The HTML for the menu is:
<div class="navbar"\>
<div class="nav-menu">
<?php wp_nav_menu( array(
'menu' => 'mobile',
'link_before' => '<span class="menu-item">',
'link_after' => '</span>',
'after' => '<span class="dropdownClick"><img class="menu-hide-me" src="...down-arrow-menu.png"></span>'
)
);?>
</div>
<div class="hamburger">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</div>
</div><!------end navbar------------>
Here's the CSS
/**------------------- sub-menu stuff------------------------**/
/**hides all dropdown arrows except for li with sub menu items**/
.menu-hide-me {
display:none;
}
.menu-item span {
color: #c9e1d1!important;
}
.menu-item-has-children .menu-hide-me {
display: inline;
width: 11px;
margin-left: 10px;
}
.sub-menu li .menu-hide-me {
display:none;
}
/**hides sub-menu**/
.sub-menu {
display:none;
}
/**open sub-menu**/
.sub-menu.sub-open {
display:block;
padding-left: 10px;
}
/**styling for links**/
.sub-menu li {
line-height:1.5!important;
}
.sub-menu a {
color: #c9e1d1;
font-size: 13px;
}
querySelectorreturns one single element (or null, if not found.) If you want to select multiple elements, you need to usequerySelectorAllinstead. (And then iterate over the elements in the resulting NodeList, if you want to do stuff such as assign individual event handlers.)