40

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?

5 Answers 5

42

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>

Sign up to request clarification or add additional context in comments.

Comments

19

HTML DOM removeAttribute() Method:

document.querySelector('button').onclick = function() {
  this.removeAttribute("class");
}
.myClass {
  background-color:red;
}

.second {
  box-shadow: 0px 0px 10px 10px;
}
<button id="button" class="myClass second">click me</button>

3 Comments

i was looking for this because edge does not support classList=' '
@EddyCharry I guess you confused classList with className.
I like this method because: it's a literal "method" - as in, it "does an action" / "performs a task" as opposed to assigning an empty string to the className property, which feels more implicit, this means it's (ever-so-slightly) more readable. Additionally, this method doesn't leave me with an empty "class" attribute in the Elements tab on devtools.
11

Use this.classname instead of this.style.className. Your Javascript code will be like this:

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

Fiddle.

Comments

1

You can remove (.style) and after that everything works fine.

 button.className = '';

or you can use this.className = "";

both works fine.

Comments

0

I use:

document.getElementById('theElementToMakeClassless').classList = null;

It's possible setting to null rather than other options has longer term effects but I haven't witnessed any in FireFox, DuckDuckGo's browser, Safari or Chrome.

Comments