To add a class to an element, you use the classList property of the element. Suppose you have an element as follows:
<div>Item</div>Code language: HTML, XML (xml)To add the box class to the <div> element, you use the following:
const div = document.querySelector('div');
div.classList.add('box');Code language: JavaScript (javascript)It’s possible to add multiple classes. The following adds three classes to the <div> element:
const div = document.querySelector('div');
div.classList.add('box','primary','rounded');Code language: JavaScript (javascript)Was this tutorial helpful ?