Tutorials Tonight
Follow Us

2 Ways JavaScript Add Class To The Elements


We are going to learn 2 different ways to add CSS classes to the elements using JavaScript. Also we will see different variation like adding multiple classes to the element, adding class to the body, creating a new element and adding class to the element, etc.

CSS can change whole world for an HTML element. A dull and ugly element can become a beautiful and attractive element. You can add CSS class to the element and make it look more attractive.

You can either directly add a class to the element as HTML attribute or use JavaScript to add a class to the element.

javascript add class

Here is an example of adding a class to an HTML element using javascript.

  • CSS
// selecting the element
let button = document.querySelector('#button');

// Add class to the element
button.addEventListener('click', function() {
  button.classList.add('.main-btn');
});
.main-btn {
  border: none;
  color: white;
  background: blue;
  padding: 10px 30px;
  border-radius: 5px;
}

@keyframes shake {
  0% { transform: translateX(0) }

  25% { transform: translateX(-5px) }

  50% { transform: translateX(0) }

  75% { transform: translateX(5px) }

  100% { transform: translateX(0) }
}

.main-btn:hover {
  animation: shake 3 0.2s ease-in-out;
}

Output: Click the button below and javascript will add a class to the button.

Click the button below.

This is a dynamic way of adding a class to an HTML element. Let's see how javascript adds class dynamically to an HTML element.


Add class javascript - 2 ways

While working on the front-end, we often need to add CSS dynamically to an HTML element. So it's better to add CSS class using javascript rather than using CSS code directly.

There are 2 ways to add CSS class using javascript.

  1. Using classList Property
  2. Using className property

1. Add class using classList property

The classList property of the HTML element returns a live representation of the element's class attribute known as DOMTokenList.

The DOMTokenList is read-only but it provides add() and remove() methods to add and remove classes.

To add a CSS class using javascript follow the steps below:

  1. Select the HTML element.
  2. Apply the classList property to it.
  3. Use the add() method to add the class and pass the class name as an argument.

Example

<p id="id1">Javascript adds a CSS class to this paragraph.</p>

<script>
  // Get the element with id="id1"
  const element = document.getElementById("id1");
  // Add a class (quote) to the element
  element.classList.add("quote");
</script>

Adding class on an event

In general, we add classes using javascript when an event occurs. For example, when a user clicks on a button, something loads, or when a user scrolls down the page, something loads.

Using the classList property's add() method you can add a class to the HTML element when an event occurs by attaching an event listener to the HTML element.

Create an event listener that selects the targeted element using javascript and add desired class to it as shown in the example below.

Example

<button onclick="addClass()">Add class to above paragraph</button>

<script>
  function addClass() {
    // Get the paragraph element
    const element = document.getElementById("id1");
    // Add a class to the paragraph
    element.classList.add("beautify");
  }
</script>

Output:

add class javascript on event

Add Multiple classes javascript

The add() method of classList property can add multiple classes at a time to the element.

To add multiple classes at once, pass multiple classes separated by a comma.

Example

<style>
  .color {
    color: white;
    background: #4e43ee;
  }

  .border {
    border-radius: 5px;
  }

  .others {
    font-size: 20px;
    padding: 15px;
  }
</style>

<button onclick="addClass()">Add classes to above paragraph</button>

<script>
  function addClass() {
    const element = document.getElementById("id1");
    // passing multiple classes separated by comma
    element.classList.add("color", "border", "others");
  }
</script>

2. Using JavaScript className property

The className property of an element can be used to get and set classes attached to the element.

It returns the classes of the element in form of string. If element has a class named class1 then it returns "class1", if element has 2 classes class1 and class2 then it returns "class1 class2", and so on.

<p class="box" id="id1">Paragraph 1</p>
<p class="big red box" id="id2">Paragtaph 2</p>

<script>
  const element1 = document.getElementById("id1");
  const element2 = document.getElementById("id2");
  console.log(element1.className); // "box"
  console.log(element2.className); // "big red box"
</script>

The className property reads as well as writes the classes of the element.

To add a new class to the element assign the class name it to the element's className property as a string.

Note: Assigning class name directly to the className property will overwrite the existing classes.

Here is an example to show this.

Example

const element = document.getElementById("id1");
element.className = "box";
// all older classes will be replaced by box

Output:

output add class classname

To add new classes without replacing older classes use the += operator to assign the new class. It will keep older classes and adds new ones.

Example

const element = document.getElementById("id1");
element.className += " box"; // must add space before class name
// new class added, old one remained

Possible mistake: Add a space before the name of the class when using className to add class. Because if the element has an old class "class1" and you add the new class "class2" it becomes "class1class2" which is meaningless to the browser.


Adding multiple classes using className

To add multiple classes assign new class names separated by spaces to the className property of the element.

Example

function addClass() {
  const element = document.getElementById("id1");
  element.className += " big box";
  // multiple classes separated by spaces
}

JavaScript add class to body

To add class to the body of the webpage select the body by document.body and use either of the 2 mentioned methods to add CSS classes.

Example

<button onclick="addClass()">Add class to body</button>

<script>
  function addClass() {
    document.body.classList.add("color")
  }
</script>

JavaScript add class to div

As mentioned above you can use any of the above 2 methods to add class to div element using javascript.

  1. Step 1: Select the element
  2. Step 2: Use either className or classList property

Example

<div id="id1">This is inside a div element</div>
<button onclick="addClass()">Add class to div</button>

<script>
  const div = document.getElementById("id1");
  function addClass() {
    div.classList.add("box");
  }
</script>

JavaScript add class to new element

Imagine a scenario where you want to add a new element to the webpage like creating a list item in a To Do list app. You can use the classList property to add a class to the new element.

To add multiple classes pass the class names separated by spaces to the classList.add() method.

Example

function createListItem() {
  const list = document.getElementById("list");
  const item = document.createElement("li");
  item.classList.add("list-item");
  item.innerHTML = "New list item";
  list.appendChild(item);
}

Add a class on hover javascript

To add a class to an element when mouse hover use onmouseover event. Attach an onmouseover event to the element trigger event handler to add the class.

Example

<div id="id1" onmouseover="addClass()">This is inside a div element</div>

<script>
  const div = document.getElementById("id1");
  function addClass() {
    div.classList.add("box");
  }
</script>

Conclusion

You can add classes to elements using className or classList property. You can add classes to the body of the webpage using document.body or document.getElementById("id").

To add a class on hover use onmouseover event. Attach an onmouseover event to the element trigger event handler to add the class.

You can add single or multiple classes to an element using any of above mensioned property.


Frequently Asked Questions

  1. How do I add a class in document getElementById?

    1. Select the element by element = document.getElementById("id")
    2. Use either element.classList.add("class") or element.className += "class"
  2. How do I delete a class in CSS?

    To delete a class in CSS you can use remove() method of classList property. Example element.classList.remove("className")

  3. How do you toggle classes in JavaScript?

    To toggle a class in JavaScript you can use toggle() method of classList property. Example element.classList.toggle("className")