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
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
.
And the result:
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:
This will make the first paragraph on this page center aligned and give it a big font size, and italicize it. Try it out yourself.