JavaScript CSS how to add and remove multiple CSS classes to an element

JavascriptHtmlCssClassAppend

Javascript Problem Overview


How can assign multiple css classes to an html element through javascript without using any libraries?

Javascript Solutions


Solution 1 - Javascript

Here's a simpler method to add multiple classes via classList (supported by all modern browsers, as noted in other answers here):

div.classList.add('foo', 'bar'); // add multiple classes

From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples

If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add() via this one-liner:

let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);

Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.

Solution 2 - Javascript

Try doing this...

document.getElementById("MyElement").className += " MyClass";

Got this here...

Solution 3 - Javascript

This works:

myElement.className = 'foo bar baz';

Solution 4 - Javascript

There are at least a few different ways:

var buttonTop = document.getElementById("buttonTop");

buttonTop.className = "myElement myButton myStyle";

buttonTop.className = "myElement";

buttonTop.className += " myButton myStyle";

buttonTop.classList.add("myElement");

buttonTop.classList.add("myButton", "myStyle");

buttonTop.setAttribute("class", "myElement");

buttonTop.setAttribute("class", buttonTop.getAttribute("class") + " myButton myStyle");

buttonTop.classList.remove("myElement", "myButton", "myStyle");

Solution 5 - Javascript

var el = document.getElementsByClassName('myclass')

el[0].classList.add('newclass');

el[0].classList.remove('newclass');

To find whether the class exists or not, use:

el[0].classList.contains('newclass'); // this will return true or false 

Browser support IE8+

Solution 6 - Javascript

You can add and remove multiple classes in same way with different in-built methods:

const myElem = document.getElementById('element-id');
//add multiple classes
myElem.classList.add('class-one', 'class-two', 'class-three');
//remove multiple classes
myElem.classList.remove('class-one', 'class-two', 'class-three');

Solution 7 - Javascript

2 great ways to ADD:

But the first way is more cleaner, since for the second you have to add a space at the beginning. This is to avoid the class name from joining with the previous class.

element.classList.add("d-flex", "align-items-center");
element.className += " d-flex align-items-center";

Then to REMOVE use the cleaner way, by use of classList

element.classList.remove("d-grid", "bg-danger");

Solution 8 - Javascript

guaranteed to work on new browsers. the old className way may not, since it's deprecated.

<element class="oneclass" />

element.setAttribute('class', element.getAttribute('class') + ' another');
alert(element.getAttribute('class')); // oneclass another

Solution 9 - Javascript

Since I could not find this answer nowhere:

ES6 way (Modern Browsers)

el.classList.add("foo", "bar", "baz");

Solution 10 - Javascript

just use this

element.getAttributeNode("class").value += " antherClass";

take care about Space to avoid mix old class with new class

Solution 11 - Javascript

Perhaps:

document.getElementById("myEle").className = "class1 class2";

Not tested, but should work.

Solution 12 - Javascript

Try this:

function addClass(element, value) {
  if(!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
}

Similar logic could be used to make a removeClass function.

Solution 13 - Javascript

In modern browsers, the [classList API][2] is [supported][1].

This allows for a (vanilla) JavaScript function like this:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';
    
    var className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];

        // Loop through the array of classes to add one class at a time
        for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
            className = classArray[j];

            element.classList.add(className);
        }
    }
};

Modern browsers (not IE) support passing multiple arguments to the classList::add function, which would remove the need for the nested loop, simplifying the function a bit:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var classList, className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];
        classList = element.classList;

        // Pass the array of classes as multiple arguments to classList::add
        classList.add.apply(classList, classArray);
    }
};

Usage

addClasses('.button', ['large', 'primary']);

Functional version

var addClassesToElement, addClassesToSelection;

addClassesToElement = function (element, classArray) {
    'use strict';

    classArray.forEach(function (className) {
       element.classList.add(className);
    });
};

addClassesToSelection = function (selector, classArray) {
    'use strict';

    // Use Array::forEach on NodeList to iterate over results.
    // Okay, since we’re not trying to modify the NodeList.
    Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
        addClassesToElement(element, classArray)
    });
};

// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])

The classList::add function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.

Resources on the classList API:

  • [Can I use][1]
  • [MDN][2]
  • [David Walsh][3]
  • [HTML5 Doctor][4]

[1]: http://caniuse.com/#feat=classlist "Can I use: classList" [2]: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList "MDN: classList" [3]: http://davidwalsh.name/classlist "David Walsh on the classList API" [4]: http://html5doctor.com/the-classlist-api "HTML5 Doctor: classList"

Solution 14 - Javascript

the Element.className += " MyClass"; is not recommended approach because it will always add these classes whether they were exit or not.

in my case, I was uploading an image file and adding classes to it, now with this each time you upload an image it will add these class whether they exist or not,

the recommended way is Element.classList.add("class1" , "class2" , "class3"); this way will not add extra classes if they already there.

Solution 15 - Javascript

Maybe this will help you learn:

//<![CDATA[
/* external.js */
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
  return doc.createElement(tag);
}
E = function(id){
  return doc.getElementById(id);
}
addClassName = function(element, className){
  var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$');
  if(!element.className.match(rx)){
    element.className += ' '+className;
  }
  return element.className;
}
removeClassName = function(element, className){
  element.className = element.className.replace(new RegExp('\s?'+className), '');
  return element.className;
}
var out = E('output'), mn = doc.getElementsByClassName('main')[0];
out.innerHTML = addClassName(mn, 'wow');
out.innerHTML = addClassName(mn, 'cool');
out.innerHTML = addClassName(mn, 'it works');
out.innerHTML = removeClassName(mn, 'wow');
out.innerHTML = removeClassName(mn, 'main');

}); // close load
//]]>

/* external.css */
html,body{
  padding:0; margin:0;
}
.main{
  width:980px; margin:0 auto;
}

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div class='main'>
    <div id='output'></div>
  </div>
</body>
</html>

Solution 16 - Javascript

  addClass(element, className1, className2){
    element.classList.add(className1, className2);
  }
  removeClass(element, className1, className2) {
    element.classList.remove(className1, className2);
  }

removeClass(myElement, 'myClass1', 'myClass2');
addClass(myElement, 'myClass1', 'myClass2');

Solution 17 - Javascript

ClassList add

var dynamic=document.getElementById("dynamic");
dynamic.classList.add("red");
dynamic.classList.add("size");
dynamic.classList.add("bold");

.red{
color:red;
}
.size{
font-size:40px;
}
.bold{
font-weight:800;
}

<div id="dynamic">dynamic css</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanonymousView Question on Stackoverflow
Solution 1 - JavascriptericsocoView Answer on Stackoverflow
Solution 2 - JavascriptRyanView Answer on Stackoverflow
Solution 3 - JavascriptmoffView Answer on Stackoverflow
Solution 4 - JavascripttheMaxxView Answer on Stackoverflow
Solution 5 - JavascriptMano bharathiView Answer on Stackoverflow
Solution 6 - Javascript1_bugView Answer on Stackoverflow
Solution 7 - Javascriptjames aceView Answer on Stackoverflow
Solution 8 - JavascriptTor ValamoView Answer on Stackoverflow
Solution 9 - JavascriptLemuresView Answer on Stackoverflow
Solution 10 - JavascriptMaged RawashView Answer on Stackoverflow
Solution 11 - JavascripttarnfeldView Answer on Stackoverflow
Solution 12 - Javascripttybro0103View Answer on Stackoverflow
Solution 13 - JavascriptLars Gyrup Brink NielsenView Answer on Stackoverflow
Solution 14 - JavascriptOmar HegaziView Answer on Stackoverflow
Solution 15 - JavascriptStackSlaveView Answer on Stackoverflow
Solution 16 - JavascriptHosseinView Answer on Stackoverflow
Solution 17 - JavascriptßãlãjîView Answer on Stackoverflow