'Check if element contains class then remove class

I can't implement the check function if (element.classList.contains(__active)). That is, if the element already contains the class "active", then you need to remove this class from the element when you click on it. Codepen



Solution 1:[1]

You can remove without checking. Try this:

const clickHandler = () => {
  document.querySelector('.active')?.classList.remove('active');
};
div {
  color: red;
  background: black;
  margin-bottom: 16px
}

div.active {
  color: black;
  background: red;
}
<div class="active">CHNAGE ME</div>
<button onClick="clickHandler()">CLICK TO CHANGE</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1