This post will discuss how to change the class of an element using JavaScript and jQuery.

1. Replace a class with another class

To replace a class with another class, you can remove the old class using jQuery’s .removeClass() method and then add the new class using jQuery’s .addClass() method.

jQuery


CSS


HTML



Edit in JSFiddle

 
In plain JavaScript, you can make use of Element.classList.remove() and Element.classList.add() methods to remove and add a class, respectively.

JS


CSS


HTML



Edit in JSFiddle

2. Replace all classes with one or more new classes

To replace all existing classes with one or more new classes, you can simply replace the content of the class attribute with the new classes. Here’s an example in jQuery demonstrating this using the .attr() method.

jQuery


CSS


HTML



Edit in JSFiddle

 
In plain JavaScript, we can do this with the className attribute.

JS


CSS


HTML



Edit in JSFiddle

3. Toggle a class

You can even implement a toggle feature in JavaScript which toggles between two classes. Here’s a working example:

JS


CSS


HTML



Edit in JSFiddle

That’s all about changing the class of an element using JavaScript and jQuery.