如何从纯JavaScript中的元素中删除一个类? [英] How to remove a class from elements in pure JavaScript?
问题描述
我想知道如何选择类名为widget和hover的所有元素,然后从这些元素中删除hover类。
I would like to know how to select all elements with class names "widget" and "hover" and then remove class "hover" from these elements.
I使用以下JavaScript代码选择具有类widget和hover的所有元素:
I have the following JavaScript code that selects all elements with class "widget" and "hover":
var elements = document.getElementsByClassName('widget hover');
console.log(elements);
这似乎工作并输出类似的东西(没有错误):
This seems to work and outputs something like this (with no errors):
[div#.widget...
问题是,如果我尝试删除hover类,我会收到错误:
The problem is that if I try to remove the class "hover", I get an error:
var elements = document.getElementsByClassName('widget hover');
console.log(elements);
elements.classList.remove("hover");
此输出:
[item: function]
length: 0
Uncaught TypeError: Cannot call method 'remove' of undefined
谁能告诉我我做错了什么?
Can anyone tell me what I'm doing wrong?
请注意我在jQuery中使用它:
Please note that I have it working in jQuery:
$('.widget.hover').removeClass('hover');
...但我正在寻找纯JavaScript的解决方案。
... but I'm looking for a solution in pure JavaScript.
推荐答案
var elems = document.querySelectorAll(".widget.hover");
[].forEach.call(elems, function(el) {
el.classList.remove("hover");
});
您可以修补。 classList
进入IE9。否则,您需要修改 .className
。
You can patch .classList
into IE9. Otherwise, you'll need to modify the .className
.
var elems = document.querySelectorAll(".widget.hover");
[].forEach.call(elems, function(el) {
el.className = el.className.replace(/\bhover\b/, "");
});
.forEach()
还需要一个IE8的补丁,但这很常见。
The .forEach()
also needs a patch for IE8, but that's pretty common anyway.
这篇关于如何从纯JavaScript中的元素中删除一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!