[javascript] JavaScript CSS how to add and remove multiple CSS classes to an element

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

This question is related to javascript html css class append

The answer is


ClassList add

_x000D_
_x000D_
var dynamic=document.getElementById("dynamic");
dynamic.classList.add("red");
dynamic.classList.add("size");
dynamic.classList.add("bold");
_x000D_
.red{
color:red;
}
.size{
font-size:40px;
}
.bold{
font-weight:800;
}
_x000D_
<div id="dynamic">dynamic css</div>
_x000D_
_x000D_
_x000D_


just use this

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

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


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.


Since I could not find this answer nowhere:

ES6 way (Modern Browsers)

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

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');

Perhaps:

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

Not tested, but should work.


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.


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

In modern browsers, the classList API is supported.

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:


Maybe this will help you learn:

_x000D_
_x000D_
//<![CDATA[_x000D_
/* external.js */_x000D_
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere_x000D_
addEventListener('load', function(){_x000D_
doc = document; bod = doc.body; htm = doc.documentElement;_x000D_
C = function(tag){_x000D_
  return doc.createElement(tag);_x000D_
}_x000D_
E = function(id){_x000D_
  return doc.getElementById(id);_x000D_
}_x000D_
addClassName = function(element, className){_x000D_
  var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$');_x000D_
  if(!element.className.match(rx)){_x000D_
    element.className += ' '+className;_x000D_
  }_x000D_
  return element.className;_x000D_
}_x000D_
removeClassName = function(element, className){_x000D_
  element.className = element.className.replace(new RegExp('\s?'+className), '');_x000D_
  return element.className;_x000D_
}_x000D_
var out = E('output'), mn = doc.getElementsByClassName('main')[0];_x000D_
out.innerHTML = addClassName(mn, 'wow');_x000D_
out.innerHTML = addClassName(mn, 'cool');_x000D_
out.innerHTML = addClassName(mn, 'it works');_x000D_
out.innerHTML = removeClassName(mn, 'wow');_x000D_
out.innerHTML = removeClassName(mn, 'main');_x000D_
_x000D_
}); // close load_x000D_
//]]>
_x000D_
/* external.css */_x000D_
html,body{_x000D_
  padding:0; margin:0;_x000D_
}_x000D_
.main{_x000D_
  width:980px; margin:0 auto;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>_x000D_
  <head>_x000D_
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />_x000D_
    <link type='text/css' rel='stylesheet' href='external.css' />_x000D_
    <script type='text/javascript' src='external.js'></script>_x000D_
  </head>_x000D_
<body>_x000D_
  <div class='main'>_x000D_
    <div id='output'></div>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


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");

  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');

This works:

myElement.className = 'foo bar baz';

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.


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");

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+


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to append

List append() in for loop ValueError: all the input arrays must have same number of dimensions Append a tuple to a list - what's the difference between two ways? How merge two objects array in angularjs? How to add an element at the end of an array? Appending a list or series to a pandas DataFrame as a row? Can someone explain how to append an element to an array in C programming? How to append elements at the end of ArrayList in Java? Append value to empty vector in R? How to append new data onto a new line