How to Add/Remove CSS Classes Using JavaScript

Follow us on LinkedIn for our latest data and tips!

This post will demonstrate two approaches for manipulating the classes of an HTML element. The first uses the plain javascript property classList and the second uses jQuery, a popular javascript library. To begin, consider the following document:


The document has one button with an onclick event to toggle the color of the button. The CSS defines classes to set the background color:

.blue {

 background: blue;


.red {

 background: red;


The only thing left to do is to implement the toggleColor() function in javascript.


Every element has a classList property containing its class attributes. This property provides methods that make it straightforward to add or remove a class.

function toggleColor() {

 var myButtonClasses = document.getElementById("btn1").classList;

 if (myButtonClasses.contains("blue")) {


 } else {



 if (myButtonClasses.contains("red")) {


 } else {




The above example uses three methods provided by classList.

  • contains() – Returns true if the element has the provided class, else returns false.
  • add() – Adds the given class to the element. This is ignored if the element already contains the specified class.
  • remove() – The provided class is removed from the element, if present.

An even simpler way to accomplish the same thing is to use the toggle() method. Which will add the provided class if it is not present, or remove it if it is:

function toggleColor() {




When working with multiple classes, simply comma separate the classes in separate strings:

document.getElementById("btn1").classList.toggle("blue”,  “bold");

document.getElementById("btn1").classList.toggle("red”,  “italics");

The only potential drawback to this approach is it was introduced in HTML5 and may not be supported if you are working with older browsers.


jQuery provides methods that function almost exactly like those shown above, but you get the added bonus of using jQuery’s shorthand for selecting elements. Here is the toggleColor() function written in jQuery:

function toggleColor() {




You could also use addClass(), removeClass(), and hasClass() to construct toggleColor() in the same manner as our first example. Note that to add multiple classes simply space separate the classes in the same string. For example:

$("#btn1").toggleClass("blue bold");

$("#btn1").toggleClass("red italics");

That’s it! Now you’re well equipped to dynamically set the appearance of DOM elements. Happy coding!