0

I'm trying to modify the w3schools accordion so that it closes all panels before opening the clicked panel:

var acc = document.getElementsByClassName("accordion-trigger");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
    acc.classList.remove("active"); //This is the line I've added
    this.classList.add("active"); //Changed to add from toggle
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
    } else {
        panel.style.maxHeight = panel.scrollHeight + "px";
    }
});
}

My modification doesn't work - I get

acc.classList is undefined

I'm familiar with jQuery syntax, but I don't understand what else I need to do here in JS. Where have I gone wrong?

user2265915
  • 539
  • 3
  • 11
  • 22
  • `acc` is an array. Note how the code already loops over that array. If you want to perform an operation on each element in that array, you'd want to loop over it as well. – David Jul 12 '21 at 17:00
  • `acc` refers to an `HTMLCollection`, which does not have a `classList` property. – Heretic Monkey Jul 12 '21 at 17:00

0 Answers0