1

I am learning Vanilla JS and DOM. Today I have a problem when I want to remove a class of all elements expect one.

const panels = document.querySelectorAll(".panel");
  function toggleOpen() {
    this.classList.toggle("open");
    console.log(panels);
  }
  function toggleActive(e) {
    if (e.propertyName.includes("flex")) {
      this.classList.toggle("open-active");
    }
  }

  panels.forEach((panel) => panel.addEventListener("click", toggleOpen));
  panels.forEach((panel) =>
    panel.addEventListener("transitionend", toggleActive)
  );

I want when I click "panel" the only panel be clicked have class "open" and remove all class "open" of all another "panel". (Exactly I want only a panel to have class "open" in all time, and it can toggle.) Thank you for your help.

1 Answer 1

1

In toggleOpen, iterate over all panels (except this one) and remove their open class first:

function toggleOpen() {
  // Close all other panels:
  for (const panel of panels) {
    if (panel !== this) {
      panel.classList.remove('open');
    }
  }
  // Either open this panel or close it:
  this.classList.toggle("open");
}
1
  • Thanks you so much. Now i know "this" can be use like that.
    – Cyan Coder
    Sep 20, 2020 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.