How to Add a Class to an Element With Vanilla JavaScript

Adding a class to an HTML element is simple when using JavaScript’s classList property method, add(). First, we take a quick look at the generic formula — and follow up with a practical example.

The formula

var element = document.querySelector("selector")
Find target element. Then add specified class to target element.

In the generic example above, we find the first HTML element on a page with the specified selector name (it could be an element selector, class selector, etc.) and store a reference to it with a variable.

Then we attach the classList property’s add() method to the element and specify the class we want to add.

Practical classList example

Let’s try finding the first paragraph element on this page you’re reading right now, and give it a class of bg-red.

var firstParagraph = document.querySelector("p")
Add this to your browser Console and hit enter.

And the result:

Adding a red background color to the first paragraph element, using the JavaScript classList property’s add method.

Note: I have the bg-red class in my website’s CSS stylesheet, that’s why it works. The class looks like this:

.bg-red {
  background-color: #cf4b32;

You can use the classList add method to add any custom class, using any CSS property, from colors to font sizes.

Add multiple classes to the same element

You can easily add numerous classes to your target element at the same time. Let’s try adding 3 classes to our first paragraph element:

var firstParagraph = document.querySelector("p")

firstParagraph.classList.add("text-center", "text-xxl", "italic")
Remember to separate each class in the add method’s arguments

This will make the first paragraph on this page center aligned and give it a big font size, and ital­i­cize it. Try it out yourself.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on