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.

<div>
  This is a block element.
</div>

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

document.querySelector("div").classList.add('my-class');

Output

<div class="my-class">
  This is a block element.
</div>
  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.

document.querySelector("div").classList.remove('my-class');

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.

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

You can add multiple classes to the selected element.

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

Output

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

Conclusion

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