To add multiple classes to an element, select the element and pass multiple classes to the classList. add() method, e.g. box. classList.
To remove multiple classes from an element, select the element and pass multiple class names to the classList. remove() method, e.g. box. classList. remove('bg-blue', 'text-white') .
toggle() The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.
To remove all classes from an element, use the removeAttribute() method, e.g. box. removeAttribute('class') . The method removes will remove the class attribute from the element, effectively removing all of the element's classes.
elem.classList.add("first");
elem.classList.add("second");
elem.classList.add("third");
is equal
elem.classList.add("first","second","third");
The new spread operator makes it even easier to apply multiple CSS classes as array:
const list = ['first', 'second', 'third'];
element.classList.add(...list);
You can do like below
Add
elem.classList.add("first", "second", "third");
Remove
elem.classList.remove("first", "second", "third");
Reference
TLDR;
In straight forward case above removal should work. But in case of removal, you should make sure class exists before you remove them
const classes = ["first","second","third"];
classes.forEach(c => {
if (elem.classList.contains(c)) {
element.classList.remove(c);
}
})
The classList
property ensures that duplicate classes are not unnecessarily added to the element. In order to keep this functionality, if you dislike the longhand versions or jQuery version, I'd suggest adding an addMany
function and removeMany
to DOMTokenList
(the type of classList
):
DOMTokenList.prototype.addMany = function(classes) {
var array = classes.split(' ');
for (var i = 0, length = array.length; i < length; i++) {
this.add(array[i]);
}
}
DOMTokenList.prototype.removeMany = function(classes) {
var array = classes.split(' ');
for (var i = 0, length = array.length; i < length; i++) {
this.remove(array[i]);
}
}
These would then be useable like so:
elem.classList.addMany("first second third");
elem.classList.removeMany("first third");
Update
As per your comments, if you wish to only write a custom method for these in the event they are not defined, try the following:
DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function(classes) {...}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function(classes) {...}
Since the add()
method from the classList
just allows to pass separate arguments and not a single array, you need to invoque add()
using apply. For the first argument you will need to pass the classList
reference from the same DOM node and as a second argument the array of classes that you want to add:
element.classList.add.apply(
element.classList,
['class-0', 'class-1', 'class-2']
);
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