How to add class to element - JavaScript

Mo Ibra

Mo Ibra

Dec 26, 2022

In this article we will learn how to add class to an element.

It is very common to add class to an element in JavaScript.


Problem

Now we have a problem, which is that we want to add a class to a specific element using JavaScript.

First we have to create a plain HTML file like this.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <!-- Added id to an element -->
    <div id="element">

    </div>

    <!-- Your JavaScript File -->
    <script src="main.js"></script>
</body>
</html>

As you can see, we created a file, created an element, and put ID on this element.

Now how will we add the class on this element?

Well, the solution to this problem is simple, Using .className property.

This property is used to add a class name to the selected element.

Syntax

element.className = "YOUR_CLASS";

Add class to element using className.

As we said before, we will add the class using className method.

// Select element
const element = document.getElementById("element");

// Add you class
element.className = "YOUR_CLASS";

Another alternative solution is to use classList.add() method.

Add class to element using classList.add() method

We can use classList.add() to add class to an element as well.

// Select element
const element = document.getElementById("element");

// Add class
element.classList.add("YOUR_CLASS");

If you want to add more than one class, you can do it:

// Select element
const element = document.getElementById("element");

// Add classes
element.classList.add("YOUR_CLASS", "ANOTHER_ONE");

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: