VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-add-a-class-to-dom-element-in-javascript/

⇱ How to Add a Class to DOM Element in JavaScript? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Add a Class to DOM Element in JavaScript?

Last Updated : 5 Aug, 2025

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:

Using classList Property

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.

Syntax:

element.classList.add("className")

Example: This example shows the implementation of the above-explained approach.

Output:

👁 addClass

Using className Property

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.

Syntax:

HTMLElementObject.className

Example: This example shows the implementation of the above-explained approach.

Output:

👁 addClass
Output
Comment