I have a long list of list items (generated via an API) and I would like to show/hide some of the items with click, something like an accordion effect.
The list items that I would like to hide by default have P-item class, and the M-item class above them is what it should be triggering them to show.
Here is my markup:
<li class="session-item M-item"></li>
<li class="session-item P-item"></li>
<li class="session-item P-item"></li>
<li class="session-item G-item"></li>
P-items are children of their parent M-item. So by default in the above example, the two P-items should be hidden and M-item and G-item should be showing. When M-item is clicked, then the two hidden P-items show. I am only listing 4 items in the above example but the list goes on and the only separator between this relationship is the G-items.
I got it to work but it's only showing/hiding the first direct sibling of M-item, I used nextElementSibling, like this:
var acc = document.getElementsByClassName("M-item");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
What's the best way to select all siblings with the P-item and then break, looks for another M-item and repeat?
Is there something similar to nextAll(); in Vanilla JS? Do I need a while loop to iterate over the next sibling?
Here's how my full markup looks like:
