How can I change an element's class with JavaScript?

Viewed 3206327

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?

33 Answers

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') )

document.getElementById("MyElement").classList.toggle('MyClass');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

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

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

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

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character

MyClass  # The literal text for the classname to remove

(?!\S)   # Negative lookahead to verify the above is the whole classname
         # Ensures there is no non-space character following
         # (i.e. must be the end of the string or space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )

### Assigning these actions to onclick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'") this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:

<script type="text/javascript">
    function changeClass(){
        // Code examples from above
    }
</script>
...
<button onclick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
    function changeClass(){
        // Code examples from above
    }

    window.onload = function(){
        document.getElementById("MyElement").addEventListener( 'click', changeClass);
    }
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)


JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');

### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);

or, without needing an id:

$(':button:contains(My Button)').click(changeClass);

You can use node.className like so:

document.getElementById('foo').className = 'bar';

This should work in Internet Explorer 5.5 and up according to PPK.

4 actions possible: Add, Remove, Check, and Toggle

Let's see multiple ways for each action.

1. Add class

Method 1: Best way to add class in the modern browser is using classList.add() method of element.

  • Case 1: Adding single class

    function addClass() {
      let element = document.getElementById('id1');
    
      // adding class
      element.classList.add('beautify');
    }
    
  • Case 2: Adding multiple class

    To add multiple class saperate classes by a comma in the add() method

    function addClass() {
      let element = document.getElementById('id1');
    
      // adding multiple class
      element.classList.add('class1', 'class2', 'class3');
    }
    

Method 2 - You can also add classes to HTML elements using className property.

  • Case 1: Overwriting pre-existing classes When you assign a new class to the className property it overwrites the previous class.
    function addClass() {
      let element = document.getElementById('id1');
    
      // adding multiple class
      element.className = 'beautify';
    }
    
  • Case 2: Adding class without overwrite Use += operator for class not to overwrite previous classes. Also add an extra space before new class.
    function addClass() {
      let element = document.getElementById('id1');
    
      // adding single multiple class
      element.className += ' beautify';
      // adding multiple classes
      element.className += ' class1 class2 class3';
    }
    

2. Remove class

Method 1 - Best way to remove a class from an element is classList.remove() method.

  • Case 1: Remove single class

    Just pass the class name you want to remove from the element in the method.

    function removeClass() {
      let element = document.getElementById('id1');
    
      // removing class
      element.classList.remove('beautify');
    }
    
  • Case 2: Remove multiple class

    Pass multiple classes separated by a comma.

    function removeClass() {
      let element = document.getElementById('id1');
    
      // removing class
      element.classList.remove('class1', 'class2', 'class3');
    }
    

Method 2 - You can also remove class using className method.

  • Case 1: Removing single class If the element has only 1 class and you want to remove it then just assign an empty string to the className method.
    function removeClass() {
      let element = document.getElementById('id1');
    
      // removing class
      element.className = '';
    }
    
  • Case 2: Removing multiple class If the element multiple classes the first get all classes from the element using className property and use replace method and replace desired classes with empty string and finally assign it to element]s className property.
    function removeClass() {
      let element = document.getElementById('id1');
    
      // removing class
      element.className = element.className.replace('class1', '');
    }
    

3. Checking class

To check if a class exists in the element you can simply use classList.contains() method. It returns true if the class exists else returns false.

function checkClass() {
  let element = document.getElementById('id1');

  // checking class
  if(element.classList.contains('beautify') {
      alert('Yes! class exists');
  }
}

4. Toggle class

To toggle a class use classList.toggle() method.

function toggleClass() {
    let element = document.getElementById('id1');

    // toggle class
    element.classList.toggle('beautify');
}

The OP question was How can I change an element's class with JavaScript?

Modern browsers allow you to do this with one line of JavaScript:

document.getElementById('id').classList.replace('span1', 'span2')

The classList attribute provides a DOMTokenList which has a variety of methods. You can operate on an element's classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), and entries().

Peter Boughton's answer is a great one, but it's now over a decade old. All modern browsers now support DOMTokenList - see https://caniuse.com/#search=classList and even Internet Explorer 11 supports some DOMTokenList methods.

Try:

element.className='second'

function change(box) { box.className='second' }
.first  { width:  70px; height:  70px; background: #ff0                 }
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
<div onclick="change(this)" class="first">Click me</div>


THE OPTIONS.

Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList to do what you want.

style vs. classList

The difference between style and classList is that with style you're adding to the style properties of the element, but classList is kinda controlling the class(es) of the element (add, remove, toggle, contain), I will show you how to use the add and remove method since those are the popular ones.


Style Example

If you want to add margin-top property into an element, you would do in such:

// Get the Element
const el = document.querySelector('#element');

// Add CSS property 
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.

classList Example

Let say we have a <div class="class-a class-b">, in this case, we have 2 classes added to our div element already, class-a and class-b, and we want to control what classes remove and what class to add. This is where classList becomes handy.

Remove class-b

// Get the Element
const el = document.querySelector('#element');

// Remove class-b style from the element
el.classList.remove("class-b")

Add class-c

// Get the Element
const el = document.querySelector('#element');

// Add class-b style from the element
el.classList.add("class-c")


For IE v6-9 (in which classList is not supported and you don't want to use polyfills):

var elem = document.getElementById('some-id');

// don't forget the extra space before the class name
var classList = elem.getAttribute('class') + ' other-class-name';

elem.setAttribute('class', classList);

classList DOM API:

A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using JavaScript. For example:

const el = document.getElementById("main");
console.log(el.classList);
<div class="content wrapper animated" id="main"></div>

We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

Example:

const el = document.getElementById('container');

function addClass () {
    el.classList.add('newclass');
}


function replaceClass () {
    el.classList.replace('foo', 'newFoo');
}


function removeClass () {
    el.classList.remove('bar');
}
button{
  margin: 20px;
}

.foo{
  color: red;
}

.newFoo {
  color: blue;
}

.bar{
  background-color: powderblue;
}

.newclass{
  border: 2px solid green;
}
<div class="foo bar" id="container">
  "Sed ut perspiciatis unde omnis
  iste natus error sit voluptatem accusantium doloremque laudantium,
  totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et
  quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
  voluptatem quia voluptas
 </div>

<button onclick="addClass()">AddClass</button>

<button onclick="replaceClass()">ReplaceClass</button>

<button onclick="removeClass()">removeClass</button>

Yes, there are many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.

const tabs=document.querySelectorAll('.menu li');

for(let tab of tabs){

  tab.onclick = function(){

    let activetab = document.querySelectorAll('li.active');

    activetab[0].classList.remove('active')

    tab.classList.add('active');
  }

}
body {
    padding: 20px;
    font-family: sans-serif;
}

ul {
    margin: 20px 0;
    list-style: none;
}

li {
    background: #dfdfdf;
    padding: 10px;
    margin: 6px 0;
    cursor: pointer;
}

li.active {
    background: #2794c7;
    font-weight: bold;
    color: #ffffff;
}
<i>Please click an item:</i>

<ul class="menu">
  <li class="active"><span>Three</span></li>
  <li><span>Two</span></li>
  <li><span>One</span></li>
</ul>

TL;DR:

document.getElementById('id').className = 'class'

OR

document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');

That's it.

And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer. It's perfect.

Note:

This is possible with (document or event):

  • getElementById()
  • getElementsByClassName()
  • querySelector()
  • querySelectorAll()
function classed(el, class_name, add_class) {
  const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
  if (add_class && !el.className.match(re)) el.className += " " + class_name
  else if (!add_class) el.className = el.className.replace(re, '');
}

Using Peter Boughton's answer, here is a simple cross-browser function to add and remove class.

Add class:

classed(document.getElementById("denis"), "active", true)

Remove class:

classed(document.getElementById("denis"), "active", false)

There is a property, className, in JavaScript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.

<!DOCTYPE html>
<html>
<head>
<title>How can I change the class of an HTML element in JavaScript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />

<center><button id="change-class">Change Class</button></center>

<script>
var change_class = document.getElementById("change-class");
change_class.onclick = function()
{
    var icon=document.getElementById("icon");
    icon.className = "fa fa-gear";
}
</script>
</body>
</html>

Credit - How To Change Class Name of an HTML Element in JavaScript

This is easiest with a library like jQuery:

<input type="button" onClick="javascript:test_byid();" value="id='second'" />

<script>
function test_byid()
{
    $("#second").toggleClass("highlight");
}
</script>

No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.

The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:

Never ever change className on-the-fly !-)

But usually you'll only need to change a property or two, and that is easily implemented:

function highlight(elm){
    elm.style.backgroundColor ="#345";
    elm.style.color = "#fff";
}
Related