JavaScript删除元素的所有类

33

我有一个按钮,当我点击它时,我想要删除所有类。目前为止,这是我尝试过的:

button.style.className = ''

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

  color:red;
  
}

.second {

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

现在我无法使用classList.remove,因为我不知道类名,它们是动态的。

我该如何从元素中删除所有类?

4个回答

36
不要从 style 对象中访问 className,直接访问它。
this.className

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

  color:red;
  
}

.second {

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


14

HTML DOM removeAttribute()方法:

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>


我正在寻找这个,因为Edge不支持classList=' '。 - Eddy Charry
@EddyCharry 我猜你把 classListclassName 搞混了。 - Gras Double

11

使用this.classname代替this.style.className。你的Javascript代码应该像这样:

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

Fiddle


1
您可以删除(.style),然后一切都可以正常工作。
 button.className = '';

或者你可以使用 this.className = "";

两种方法都可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接