I have a sidebar navigation menu (HTML5/CSS/Vanilla JavaScript) that acts like an accordion with multiple levels of nested menus. Everything is working so far in terms of hiding and showing menus and applying the correct styles for the various states EXCEPT for 1 thing.
If a parent menu is expanded (displaying a sub-menu) and one of its children is also expanded to show a sub-sub-menu... kinda like this:
- Menu Item 1
- Menu Item 2
|_ Item 2.1
|_ Item 2.1.1
|_ Item 2.1.2
|_ Item 2.2
- Menu item 3
|_ Item 3.1
Clicking any item with sub-items (Ex: Menu Item 2
or Menu Item 2.1
should not only hide ALL of the menu (and sub-menu) items, but it should also collapse all of the sub-menus nested within that parent so that when you click an item with sub-menus again (to display it), thy are all "reset" back to their original state, BUT this should only apply to the items and menus nested under the item clicked.
Clicking Menu Item 2
should produce this:
- Menu Item 1
- Menu Item 2
- Menu item 3
|_ Item 3.1
Instead it's producing this:
- Menu Item 1
- Menu Item 2
- Menu item 3
ALL of the submenus (regardless of which item its nested under) are being collapsed and hidden.
The lines pertaining to this are
const allItems = clicked.parentElement.querySelectorAll("li");
const allMenus = clicked.closest('.nav-list').querySelectorAll("ul");
allItems.forEach((item) => item.classList.remove("selected"));
allMenus.forEach((menu) => {
This.hide(menu);
menu.classList.toggle('open');
});
It's got to be something right in front of me, but I can't seem to isolate it. Any help would be greatly appreciated. Please also feel free to shoot holes in anything else you see that doesn't quite qualify as "best practices".