Javascript 如何从所有元素中删除特定类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26362423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:47:53  来源:igfitidea点击:

How to remove a specific class from all elements?

javascriptjquery

提问by Afghan Dev

How do I remove a given class from the page elements?

如何从页面元素中删除给定的类?

Example:

例子:

<div class="fan light"> ... </div>
<div class="light"> ... </div>
<h3 class="seahorse light"> SomeHeading </h3>

I want to drop the class lightfrom all elements of the page!

我想light从页面的所有元素中删除该类!

How do I do that using jquery or javascript?

我如何使用 jquery 或 javascript 做到这一点?

回答by Pointy

Just find all the elements that dohave the class, and remove it:

只要找到所有的元素有类,并将其删除:

$(".light").removeClass("light");

With plain JavaScript:

使用纯 JavaScript:

var lights = document.getElementsByClassName("light");
while (lights.length)
    lights[0].className = lights[0].className.replace(/\blight\b/g, "");

(That relies on the browser supporting .getElementsByClassName().) Note that the loop looks a little weird, always operating on element 0 of the element list. That's because the lists returned from APIs like .getElementsByClassName()are live— they change to reflect changes in the DOM. When a class is removed from an element, it's no longer in the list of elements with that class name. Thus by removing the class from the first element in the list, that element goes away. Eventually the list will be empty. (I've always thought that this was a bizarre behavior that flagrantly violates the principle of least surprise, but there you go.)

(这依赖于支持 的浏览器.getElementsByClassName()。)请注意,循环看起来有点奇怪,它总是在元素列表的元素 0 上运行。这是因为从 API 返回的列表.getElementsByClassName()实时的——它们会发生变化以反映 DOM 中的变化。当一个类从一个元素中移除时,它就不再出现在具有该类名的元素列表中。因此,通过从列表中的第一个元素中删除类,该元素就会消失。最终列表将是空的。(我一直认为这是一种奇怪的行为,公然违反了最小惊喜原则,但你去了。)

Finally it's pointed out in a comment that newer browsers (IE10+) support a DOM element property called .classList. It's a list of class names, plus it supports some handy methods. In particular:

最后,在评论中指出,较新的浏览器 (IE10+) 支持名为.classList. 它是一个类名列表,此外它还支持一些方便的方法。特别是:

var lights = document.getElementsByClassName("light");
while (lights.length)
    lights[0].classList.remove("light");

回答by xandercoded

Use jQueryto find all DOMelements with the classlightand remove the class.

使用jQuery找到所有DOM与元素classlight和删除class

$('.light').removeClass('light');

回答by Vasin Yuriy

Short plain JavaScript:

简短的纯 JavaScript:

[].forEach.call(document.querySelectorAll('light'), function (el) {
    el.classList.remove('hidden');
});