# Is there a way to add/remove several classes in one single instruction with classList in HTML and JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

The classList property returns the class name(s) of an element, as a DOMTokenList object. The classList property is read-only, however, you can modify it by using the add() and remove() methods.

The classListproperty 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 addMany function and removeMany to DOMTokenList

These would then be useable like so −

DOMTokenList.prototype.addMany = function(classes) {
var arr = classes.split(' ');
for (var j = 0, length = arr.length; j < length; j++) {
this.add(array[j]);
}
}
Published on 21-Mar-2018 09:37:23
Advertisements