简体   繁体   English

如何从纯 JavaScript 中的元素中删除一个类?

[英]How to remove a class from elements in pure JavaScript?

I would like to know how to select all elements with class names "widget" and "hover" and then remove class "hover" from these elements.我想知道如何选择所有类名为“widget”和“hover”的元素,然后从这些元素中删除类“hover”。

I have the following JavaScript code that selects all elements with class "widget" and "hover":我有以下 JavaScript 代码,用于选择具有“widget”和“hover”类的所有元素:

var elements = document.getElementsByClassName('widget hover');
console.log(elements);

This seems to work and outputs something like this (with no errors):这似乎有效并输出如下内容(没有错误):

[div#.widget... 

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");

This outputs:这输出:

[item: function]
length: 0
Uncaught TypeError: Cannot call method 'remove' of undefined 

Can anyone tell me what I'm doing wrong?谁能告诉我我做错了什么?


Please note that I have it working in jQuery:请注意,我在 jQuery 中使用了它:

$('.widget.hover').removeClass('hover');

... but I'm looking for a solution in pure JavaScript. ...但我正在寻找纯 JavaScript 的解决方案。

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.classList.remove("hover");
});

You can patch .classList into IE9.您可以将.classList修补到 IE9 中。 Otherwise, you'll need to modify the .className .否则,您需要修改.className

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.className = el.className.replace(/\bhover\b/, "");
});

The .forEach() also needs a patch for IE8, but that's pretty common anyway. .forEach()也需要一个针对 IE8 的补丁,但无论如何这很常见。

Find elements:查找元素:

var elements = document.getElementsByClassName('widget hover');

Since elements is a live array and reflects all dom changes you can remove all hover classes with a simple while loop:由于elements是一个live数组并反映所有 dom 更改,因此您可以使用简单的 while 循环删除所有hover类:

while(elements.length > 0){
    elements[0].classList.remove('hover');
}

It's 2021... keep it simple and just use es6现在是 2021 年...保持简单,只需使用 es6

Times have changed and now the cleanest and most readable way to do this is:时代变了,现在最干净、最易读的方法是:

Array.from(document.querySelectorAll('.widget.hover')).forEach((el) => el.classList.remove('hover'));

If you can't support arrow functions then just convert it like this:如果您不能支持箭头函数,则只需将其转换为:

Array.from(document.querySelectorAll('.widget.hover')).forEach(function(el) { 
    el.classList.remove('hover');
});

Additionally if you need to support extremely old browsers then use a polyfil for the forEach and Array.from and move on with your life.此外,如果您需要支持非常旧的浏览器,那么forEachArray.from使用polyfil ,然后继续您的生活。

elements is an array of DOM objects.元素是一个 DOM 对象数组。 You should do something like this你应该做这样的事情

for (var i = 0; i < elements.length; i++) {
   elements[i].classList.remove('hover');
}

ie: enumerate the elements collection, and for each element inside the collection call the remove method即:枚举元素集合,并为集合内的每个元素调用remove方法

This might help这可能有帮助

let allElements = Array.from(document.querySelectorAll('.widget.hover'))
for (let element of allElements) {
  element.classList.remove('hover')
}

For ES6, this can be done in a few ways with one liners , where you create an array of the elements with the spread operator ... , and remove the class with the map operator:对于 ES6,这可以通过一个 liners以几种方式完成,您可以在其中使用扩展运算符...创建元素数组,并使用map运算符删除类:

With querySelectorAll :使用querySelectorAll

[...document.querySelectorAll('.widget')].map(x => x.classList.remove('hover'));

With getElementsByClassName :使用getElementsByClassName

[...document.getElementsByClassName('widget')].map(x => x.classList.remove('hover'));

For querySelectorAll , notice the use of .widget instead of widget .对于querySelectorAll ,请注意使用.widget而不是widget An alternative for the spread operator would be to use Array.from like:扩展运算符的替代方法是使用Array.from例如:

Array.from(document.querySelectorAll('.widget')).map(x => x.classList.remove('hover'));

鉴于为我工作。

document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));
var elems = document.querySelectorAll(".widget.hover");

 for(let elem of elems){
        elem.classList.remove('hover');
        }

I use a simple method.我用一个简单的方法。 If you always process [0] in the required number of loops, you can apply the process to all.如果您始终在所需的循环次数中处理 [0],则可以将该处理应用于所有循环。

The HTMLCollection( elements ) changes in real time, so put the length in a variable. HTMLCollection( elements ) 实时变化,因此将长度放入变量中。 ( l = element.length ) ( l = element.length )

for(var elements=document.getElementsByClassName('widget hover'),i=0,l=elements.length; l>i; i++) {
  elements[0].classList.remove("hover");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM