How to Add a Class to an Element in JavaScript

To add a class to a given element in JavaScript, you can use the “element.classList.add()” method.

The add() method of the DOMTokenList Interface for modern browsers adds the given token to the list.

Syntax

element.classList.add("your_class_name");

You can also add multiple classes to your HTML elements.

element.classList.add("class_1", "class_2", "class_3")

Example

The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list.

Let’s create a CSS file called style.css and add the following code.

.data {
   color: red;
   font-size: 20px;
}

Now let’s write an HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
  <p>
    Adding class using JavaScript
  </p>
</body>
</html>

We included a stylesheet using <link> tag.

Now, we will add a class using element.classList.add() method to the <p> element using code.

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
 </head>
 <body>
  <p>
    Adding class using JavaScript
  </p>
 <script type="text/javascript">
   let p = document.querySelector("p");
   p.classList.add("data");
 </script>
 </body>
</html>

You can see that <script> where we first selected an <p> element using document.querySelector() function and then use that variable to add the class “data,” If you run this file in the browser, you will see the following output.

Javascript add class

That’s it. We successfully added a class to the element using element.classList.add() method.