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.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.