JavaScript:在多个元素上添加/删除单个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23565551/
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
JavaScript: Add/remove a single class on multiple elements
提问by user3143218
How can I add/remove a single class on multiple class-selected elements.
如何在多个类选择的元素上添加/删除单个类。
In my setup I have some variables cached for doesn't stuff to each:
在我的设置中,我缓存了一些变量,而不是每个变量:
var classOne = document.querySelector(".class1");
var classTwo = document.querySelector(".class2");
var classThree = document.querySelector(".class3");
var classFour = document.querySelector(".class4");
but I'm also trying to do something like this:
但我也在尝试做这样的事情:
var allClasses = [classOne, classTwo, classThree, classFour];
allClasses.classList.add("active");
allClasses.classList.remove("active");
Doesn't seem to be working though.
虽然似乎没有工作。
No jQuery please.
请不要使用jQuery。
回答by bottens
Try this:
试试这个:
var classOne = document.querySelector(".class1");
var classTwo = document.querySelector(".class2");
var classThree = document.querySelector(".class3");
var classFour = document.querySelector(".class4");
var allClasses = [classOne, classTwo, classThree, classFour];
allClasses.forEach(function(el) {
el.classList.add("active")
})
回答by Fabian von Ellerts
Now this can be simplified to:
现在这可以简化为:
document.querySelectorAll('.class1, .class2, .class3, .class4').forEach(el => el.classList.add('active'))
If you need legacy browser support, use a regular function or transpileand include this polyfill:
如果您需要旧版浏览器支持,请使用常规函数或转译并包含此polyfill:
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function (callback, thisArg) {
thisArg = thisArg || window
for (let i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this)
}
}
}
If you use querySelectorAll
a lot, you can bind it to a variable:
如果你使用querySelectorAll
很多,你可以将它绑定到一个变量:
const $$ = document.querySelectorAll.bind(document)
$$('.class1, .class2, .class3, .class4').forEach(el => el.classList.add('active'))