简体   繁体   中英

How to remove a previously toggled class when we toggle another class by click event

I dont use Jquery and dont want to , I wanted to toggle a class again once next item is toggled with same class. so the class from previous one is removed. and only one class is toggled on at a time.

I tried adding document.getElementsByClassName(".panel").removeClass("open"); to the function to first remove all toggled class('open') but that doesnt work. i tried adding an id and trying to remove a class from that id still doesn't work

function toggleOpen() {

     document.getElementsByClassName(".panel").removeClass("open");//this give me error
      this.classList.toggle('open');


    }
    function toggleActive(e) {
      if (e.propertyName.includes('flex')) {
        this.classList.toggle('open-active');
      }

    }



    const panels = document.querySelectorAll('.panel');
    panels.forEach(panel => panel.addEventListener('click', toggleOpen));
    panels.forEach(panel => panel.addEventListener('transitionend', toggleActive));

Result

Uncaught TypeError: document.getElementsByClassName(...).removeClass is not a function

It should be classList.remove("open") , not removeClass("open")

Also, it wouldn't work because getElementsByClassName would return a collection of elements, and you can't remove the class from them all at once. You'd have to call it for each element in the panel.

Array.from(document.getElementsByClassName(".panel")).forEach(element => element.classList.remove("open"))

Or without turning it to an array first you can do

const panels = document.getElementsByClassName(".panel")
for (let panel of panels) {
  panel.classList.remove("open")
}

Since you are adding event listener to each element, document.getElementsByClassName(".panel").removeClass("open"); is not required. this inside the function will refer to clicked element.

removeClass is jquery method, which will not be available. document.getElementsByClassName returns list of elements, so you need to loop over it.

Try following example.

 function toggleColor() { this.classList.toggle('red'); } const panels = document.querySelectorAll('.panel'); panels.forEach(panel => panel.addEventListener('click', toggleColor)); 
 .green { color: green; } .red { color: red; } 
 <p class="panel green">H1<p> <p class="panel red">H2<p> <p class="panel green">H3<p> <p class="panel red">H4<p> 

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