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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much. Now i know "this" can be use like that.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.