How to Add a CSS Class to an Element using JavaScript

Updated onbyAlan Morel
How to Add a CSS Class to an Element using JavaScript

The easiest way to customize and control the front-end UI of a webpage is to utilize CSS classes.

Sometimes, you need to add a class on an element on the fly, and for that we can use JavaScript.

In this post, we'll learn how to use JavaScript to add a CSS class to an element.

How to add a CSS class to an element using JavaScript

To add a CSS class to an element, let's first look at some example HTML:

HTML
<div class="my-element">My element</div>

Let's say we want to add the class my-class to the element with the class my-element.

We want the result to look like this:

HTML
<div class="my-element my-class">My element</div>

First, we'll need to query the DOM for this element using the querySelector() method:

JAVASCRIPT
const myElement = document.querySelector(".my-element");

Now that we have the element, we can use the built-in classList property to add the class.

This property is an object that contains a list of all the classes on the element.

It contains an add method that we can use to add a class to the element.

JAVASCRIPT
const myElement = document.querySelector(".my-element"); myElement.classList.add("my-class");

When this code runs, the markup will be updated to look like this:

HTML
<div class="my-element my-class">My element</div>

If you want to add multiple classes to this element, you can still use the add method, just pass in multiple classes as arguments:

JAVASCRIPT
const myElement = document.querySelector(".my-element"); myElement.classList.add("my-class", "another-class", "yet-another-class");

This will add all three classes to the element, so the result looks like this:

HTML
<div class="my-element my-class another-class yet-another-class">My element</div>

Conclusion

In this post, we learned how to use JavaScript to add a CSS class to an element.

Simply use the classList property to access the list of classes on the element, and then use the add method to add a class to the element.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.