How Can I Change an Element's Class with JavaScript?

The class attribute in HTML is used to define a class for one or more HTML elements. On the other hand the HTML id attribute is used to specify a unique id for an HTML element.

You can't have more than one element with the same id in an HTML document.

Many elements can contain the same class. So that we don't have to write the same style for every element over and over again.

If you are working in html, css and javascript, you must know that how to change the class of an element dynamically in JavaScript.

Even, if you are thinking to implement the dark/light mode on your webpage, it can be done with changing the element's class.

In this article, we’ll try to understand how to change an element’s class with JavaScript.

The classList Property

The classList property gives us some built-in methods to manipulate the CSS classes. ( add(), remove() etc.)

The Example.

Suppose, you have a div element.

  This is a block element.

To change the class of this element, write the following code inside the script element.



<div class="my-class">
  This is a block element.
  1. Select the div element with querySelector() method.
  2. Each element has a classList property.
  3. I called a built-in method called add().
If the target element contains the same class, nothing is done.

Remove an element's class.

If an element already has a class, we can remove that class using the remove() method.

Example of remove() method.


The className Property.

The className property is used to set a value to a CSS class directly.

Write the following code to add a new class to the targeted element.


You can add multiple classes to the selected element.

document.querySelector("div").className='my-class new-class';


<div class="my-class new-class">
  This is a block element.


In this article, you have learned how to change an element's class with javascript.