How to set an HTML element’s class using JavaScript

In this article, we will show you how to add / remove / toggle an HTML element’s class using JavaScript. There are two different properties called className and classList to modify the class of an HTML element in JavaScript.

Let’s consider the following HTML element for demonstration of the className property.

Get class name

Set class name

The classList methods

Let’s talk about the classList methods to add, remove, toggle and replace the class. Use the following HTML element for demonstration.

Add Class

Use the classList.add() method to add the class.

Remove Class

Let’s use the classList.remove() method to remove the class.

Toggle Class

Now use the classList.toggle() method to toggles a given class on an object.

Replace Class

Use the classList.replace() method to replace the class.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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