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.
To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element.
How to use addClass() and removeClass() to remove one class name, and add a new class name. Using a function to remove a class from the selected elements.
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")
})
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 transpile and include this 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:
const $$ = document.querySelectorAll.bind(document)
$$('.class1, .class2, .class3, .class4').forEach(el => el.classList.add('active'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With