How to add a CSS class to an element using JavaScript

published: 02 Oct 2022

2 min read

How to add a CSS class to an element using JavaScript

To add a CSS class to an HTML element, you can use the classList property of the element. It is a read-only property that returns a live DOMTokenList collection of all the classes applied to the element.

Let us say you have the following HTML element:

<div>🍕</div>

To add the pizza class to the above <div> element, you can use the following code:

const div = document.querySelector('div');

div.classList.add('pizza');

The classList.add() method also allows you to add multiple classes:

const div = document.querySelector('div');

div.classList.add('pizza', 'spice', 'potato');

The classList property only works in modern browsers, and IE10 and above.

Take a look at this article to learn more about adding, removing, and toggling CSS classes in JavaScript.

How to add a CSS class to an element using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming