Search code examples
javascripthtmlcss

Js remove all classes from element


I have a button and when I click on it I want to remove all the classes. That's what I've tried so far:

button.style.className = ''

document.querySelector('button').onclick = function() {
  this.style.className = '';
}
.myClass {

  color:red;
  
}

.second {

  color:green;
}
<button class="myClass second">click me</button>

Now I can't use classList.remove because I doen't know the class names, they are dynamic.

How can I remove all the classes from an element?


Solution

  • Do not access className from the style object, access it directly like

    this.className
    

    document.querySelector('button').onclick = function() {
      this.className = '';
    }
    .myClass {
    
      color:red;
      
    }
    
    .second {
    
      color:green;
    }
    <button id="button" class="myClass second">click me</button>