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


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]);
   }
}

Updated on: 24-Jun-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements