How do you add a class to an element in JavaScript?

In JavaScript, you can add a class to an element using the classList property, which is available on DOM (Document Object Model) elements.

For example:

// Select the element you want to add a class to
const element = document.getElementById("myElement");

// Add a class to the element
element.classList.add("myClass");

In the above example, getElementById("myElement") is used to select an element with the id attribute of “myElement”. The classList.add("myClass") method is then called on the selected element, with “myClass” being the name of the class you want to add.

You can also add multiple classes at once by passing them as separate arguments to the classList.add() method, like this:

// Add multiple classes to the element
element.classList.add("class1", "class2", "class3");

This will add “class1”, “class2”, and “class3” to the class list of the element.

Note: classList is supported in modern browsers. If you need to support older browsers, you may need to use alternative methods such as modifying the className property.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: