更新时间:2023-12-03 09:07:04
getElementsByClassName 返回实时 HTMLCollection 对象,从元素中删除类时会更新。
getElementsByClassName returns a live HTMLCollection object, which gets updated when you remove the class from the elements.
因此,您可以使用的一个简单逻辑是使用while循环并查看是否该集合包含任何项目,如果是这样,则从第一项中删除该类。
So one simple logic you can use is to use a while loop and see if the collection has any items, if so remove the class from the first item.
function removeClass() {
var elements = document.getElementsByClassName("test");
console.log("Length " + elements.length)
while (elements.length) {
elements[0].setAttribute("class", "");
}
}
.test {
color: red;
}
<span class="test" id="test1">Test1 </span>
<span class="test" id="test2">Test2 </span>
<span class="test" id="test3">Test3 </span>
<button onclick="removeClass()">Test</button>