简体   繁体   中英

How to remove a class of all element expect one in one Array

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.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM