Change an html element’s class with JavaScript and jQuery

Changing Classes with JavaScript
To dynamically change class(es) of an html element using Javascript, you can use classList method:

if ( document.getElementById(“MyElement”).classList.contains(‘MyClass’) ) { … }

To change all classes for an element:

document.getElementById(“MyElement”).className = “MyClass”;
document.getElementById(“MyElement”).className = “MyClass1 MyClass2”;

The above commands will overwrite the existing classes; to add a class without removing/affecting existing values append the new class name (don’t forget a space before name):

document.getElementById(“MyElement”).className += ” MyClass”;

Warning! The above commands doesn’t work on IE < v10.

To remove a single class to an element, without affecting other potential classes, you can use a simple regex replace:

document.getElementById(“MyElement”).className = document.getElementById(“MyElement”).className.replace(/(?:^|\s)MyClass(?!\S)/g , ”);

(‘(?:^|\s)‘ match the start of the string, or any single whitespace character, ‘MyClass‘ is the classname to remove, ‘(?!\S)‘ verify the above is the whole classname, ‘g‘ tells the replace to repeat as required, if class name has been added multiple times)

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

if ( document.getElementById(“MyElement”).className.match(/(?:^|\s)MyClass(?!\S)/) ) { … }

You can assign a class change to a click event just adding a change function (ex. changeClass); there are two ways to do that.
The first one is to create the function and call it in the onclick attribute:

<script type=”text/javascript”>
function changeClass(){
// Your code for class change (as above)
<button onclick=”changeClass()”>My Button</button>

It is not required to have this code in script tags, you can include it in a file.

The second way is to move the onclick event into JavaScript (e.g. using addEventListener):

<script type=”text/javascript”>
function changeClass(){
// Your code for class change (as above)
window.onload = function(){
document.getElementById(“MyElement”).addEventListener( ‘click’, changeClass);
<button id=”MyElement”>My Button</button>

NOTE: in this case the ‘window.onload‘ 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.

Changing Classes with jQuery

It’s possible to get the same results using jQuery:

if ( $(‘#MyElement’).hasClass(‘MyClass’) ) { … }

jQuery provides also a shortcut for adding a class if it doesn’t apply, or removing a class that does:


To assign class change to a click event just use the change function:


or, without needing an id:

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

Leave a comment

Your email address will not be published. Required fields are marked *