As the title of this thread suggests, I'm trying to add classes to divs using data attributes in vanilla javascript. However, I'm not sure I'm going about it the most efficient way.
Below I've added some basic HTML and javascript. If anyone can help me fill in the blanks, I would appreciate it greatly.
var selector_mastmenu = document.getElementById("menu");
selector_mastmenu.addEventListener('click', function(event) {
if(event.target.classList.contains("has-child")) {
// Remove class `show` from all `menu__panel` divs.
// Find `menu__panel` with matching `data-menu-id` and add class `show`.
}
if(event.target.classList.contains("panel__back")) {
// Remove class `show` from all `menu__panel` divs.
// Find `parent-menu-id` of `menu__panel` add class `show` to `menu-id`.
}
});
#menu .menu__panel {
display: none;
}
#menu .menu__panel.show {
display: block;
}
<div id="menu">
<div class="menu__panel" data-menu-id="2_1" data-parent-menu-id="1">
<button class="panel__back" type="button">Return to Main Menu</button>
<ul class="panel__menu">
<li><a href="#">Second Level Menu Item</a></li>
<li><a href="#">Second Level Menu Item</a></li>
<li><a href="#">Second Level Menu Item</a></li>
</ul>
</div>
<div class="menu__panel show" data-menu-id="1">
<ul class="panel__menu">
<li><a href="#" class="has-child" data-menu-id="2_1">Menu Item</a></li>
</ul>
</div>
</div>
document.querySelectorAll(selector)to target all elements matching a given selector.