![]() |
VOOZH | about |
Adding a class to a DOM (Document Object Model) element in JavaScript is a fundamental task that enables developers to dynamically manipulate the appearance and behavior of web pages. Classes in HTML provide a powerful way to apply CSS styles or JavaScript functionality to multiple elements at once.
By using JavaScript, you can easily add, remove, or toggle classes on elements, making your web applications more interactive and responsive to user actions.
These are the following approaches:
Table of Content
In this approach, we are using classList property to add the class into the DOM element. It returns the class name as a DOMTokenList object. It has a method called “add” which is used to add class name to elements. we will access the div using the getElementById and we will use the add property of classList to add a class.
element.classList.add("className")Example: This example shows the implementation of the above-explained approach.
Output:
In this approach, we are using the clasName property. This property returns the className of the element. If the element has already a class then it will simply add another one to it or else it will append our new class to it.
HTMLElementObject.classNameExample: This example shows the implementation of the above-explained approach.
Output: