Is there a way to add / remove multiple classes in the same command with classList?

So far I have to do this:

elem.classList.add("first"); elem.classList.add("second"); elem.classList.add("third"); 

While this is possible in jQuery, for example

 $(elem).addClass("first second third"); 

I would like to know if there is any native way to add or remove.

+59
javascript html5
Jun 20 2018-12-12T00:
source share
11 answers
 elem.classList.add("first"); elem.classList.add("second"); elem.classList.add("third"); 

equally

 elem.classList.add("first","second","third"); 
+113
Jan 21 '13 at 3:37
source share

The new operator simplifies the use of several CSS classes as an array:

 const list = ['first', 'second', 'third']; element.classList.add(...list); 
+17
Apr 07 '16 at 20:34
source share

The classList property ensures that duplicate classes are not added unnecessarily to the element. To preserve this functionality, if you don't like the longhand version or the jQuery version, I would suggest adding the addMany and removeMany to the DOMTokenList (type 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]); } } 

Then they will be used as follows:

 elem.classList.addMany("first second third"); elem.classList.removeMany("first third"); 

Update

According to your comments, if you want to write your own method for them, if they are not defined, try the following:

 DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function(classes) {...} DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function(classes) {...} 
+15
Jun 20 2018-12-12T00:
source share

Since the add() method of classList simply allows you to pass individual arguments, rather than a single array, you need to set add() with apply. For the first argument, you need to pass the classList link from the same DOM node, and as the second argument, the array of classes you want to add:

 element.classList.add.apply( element.classList, ['class-0', 'class-1', 'class-2'] ); 
+8
Feb 26 '16 at 0:52
source share

Newer versions of the DOMTokenList specification allow several add() and remove() arguments, as well as a second toggle() argument to force state.

During recording, Chrome supports several add() and remove() arguments, but none of the other browsers do. IE 10 and below, Firefox 23 and below, Chrome 23 and below, and other browsers do not support the second argument toggle() .

I wrote the following little polyfill to cover me until the support expands:

 (function () { /*global DOMTokenList */ var dummy = document.createElement('div'), dtp = DOMTokenList.prototype, toggle = dtp.toggle, add = dtp.add, rem = dtp.remove; dummy.classList.add('class1', 'class2'); // Older versions of the HTMLElement.classList spec didn't allow multiple // arguments, easy to test for if (!dummy.classList.contains('class2')) { dtp.add = function () { Array.prototype.forEach.call(arguments, add.bind(this)); }; dtp.remove = function () { Array.prototype.forEach.call(arguments, rem.bind(this)); }; } // Older versions of the spec didn't have a forcedState argument for // `toggle` either, test by checking the return value after forcing if (!dummy.classList.toggle('class1', true)) { dtp.toggle = function (cls, forcedState) { if (forcedState === undefined) return toggle.call(this, cls); (forcedState ? add : rem).call(this, cls); return !!forcedState; }; } })(); 

A modern browser is expected in compliance with ES5 and DOMTokenList , but I use this polyfill in several specially designed environments, so it works fine for me, but it may need to be configured for scripts that will run in legacy browsers like IE 8 and lower.

+5
Apr 26 '14 at 21:22
source share

To add a class to an element

 document.querySelector(elem).className+=' first second third'; 

UPDATE:

Delete class

 document.querySelector(elem).className=document.querySelector(elem).className.split(class_to_be_removed).join(" "); 
+3
Jun 20 2018-12-12T00:
source share

The standard definition only allows you to add or remove one class. A few small wrapper functions can do what you ask for:

 function addClasses (el, classes) { classes = Array.prototype.slice.call (arguments, 1); console.log (classes); for (var i = classes.length; i--;) { classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/); for (var j = classes[i].length; j--;) el.classList.add (classes[i][j]); } } function removeClasses (el, classes) { classes = Array.prototype.slice.call (arguments, 1); for (var i = classes.length; i--;) { classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/); for (var j = classes[i].length; j--;) el.classList.remove (classes[i][j]); } } 

These wrappers allow you to specify a list of classes as separate arguments, as lines with space or commas, or a combination. For an example see http://jsfiddle.net/jstoolsmith/eCqy7

+2
Jun 20 2018-12-12T00:
source share

Here is a job for IE 10 and 11 users who looked pretty straight forward.

 var elem = document.getElementById('elem'); ['first','second','third'].map(item => elem.classList.add(item)); 
 <div id="elem">Hello World!</div> 

or

 var elem = document.getElementById('elem'), classes = ['first','second','third']; classes.map(function(item) { return elem.classList.add(item); }); 
 <div id="elem">Hello World!</div> 
+1
Jun 29 '17 at 21:33
source share

I liked the @ rich.kelly answer, but I wanted to use the same nomenclature as classList.add() (comma separated lines), so a slight deviation.

 DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function() { for (var i = 0; i < arguments.length; i++) { this.add(arguments[i]); } } DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function() { for (var i = 0; i < arguments.length; i++) { this.remove(arguments[i]); } } 

So you can use:

 document.body.classList.addMany('class-one','class-two','class-three'); 

I need to test all browsers, but it worked for Chrome.
Should we check for something more specific than the existence of DOMTokenList.prototype.addMany ? What exactly causes classList.add() to fail in IE11?

0
May 19 '15 at 2:56
source share

Another polyfill for element.classList is here . I found it through MDN .

I include a script and use element.classList.add("first","second","third") , as intended.

0
Jan 16 '16 at 17:25
source share

Suppose you have a set of classes to add, you can use the ES6 distribution syntax:

let classes = ['first', 'second', 'third']; elem.classList.add(...classes);

0
May 23 '17 at 8:06 a.m.
source share



All Articles