Introduction
In this short tutorial, we are going to see how to change a HTML element class using javascript.
If you want to change the class you can use the following code:
document.getElementById("ElementId").className = " NewClass";
Read below for more alternatives and examples.
Using HTML5 class list
Modern browsers support using the classList
to add and remove classes fo an element.
The next code will add NewClass
to the element with id ElementId
:
document.getElementById("ElementId").classList.add('NewClass');
classList has the following methods:
- add
- remove
- contains
- toggle
Using jQuery
If you are using jQuery here are some examples:
$('#ElementId').addClass('NewClass'); // add class
$('#ElementId').removeClass('NewClass'); // remove class
if ( $('#ElementId').hasClass('NewClass') ) // check if element has certain class
Using jQuery is very similar to HTML5 version.
Using className (old browsers)
You can also use className
which is a string.
The same example as before could be implemented as:
document.getElementById("ElementId").className += " NewClass";
Note that we contact string to add a new class.
If you want to remove a class using the className method is more difficult since you have to remove a work inside a string using javascript. The same applies if you want to check if an element has certain class.
To check is a element has certain class:
document.getElementById("ElementId").className.match(/(?:^|\s)ElementId(?!\S)/)