How to Change an Element’s Class with JavaScript

To change an element’s class with JavaScript, you can use the “className” attribute.

The document.getElementById() method is used to return the element in the document with the “id” attribute, and the “className” attribute can be used to change/append the class of the element.

Syntax

document.getElementById("myElement").className = "myclass";

Example 1: Changing an element’s class

We will change the class name on the button click.

<!DOCTYPE html>
<html>

<head>
 <title>Change Class Name</title>
 <style>
   .oldClass {
     color: blue;
   }

   .newClass {
     color: red;
   }
 </style>
</head>

<body>
 <p id="myElement" class="oldClass">Hello, World!</p>
 <button onclick="changeClass()">Change Class</button>

 <script>
  function changeClass() {
    var element = document.getElementById("myElement");
    element.className = "newClass";
  }
 </script>
</body>

</html>

Before changing the class name

Before changing the class name

After changing the class name

After changing the class name

Example 2: Toggle between two class names

<!DOCTYPE html>
<html>

<head>
 <title>Toggle Class Name</title>
 <style>
   .class1 {
     color: blue;
   }

   .class2 {
     color: red;
   }
 </style>
</head>

<body>
  <p id="myElement" class="class1">Hello, World!</p>
  <button onclick="toggleClass()">Toggle Class</button>

  <script>
   function toggleClass() {
     var element = document.getElementById("myElement");
     if (element.className === "class1") {
       element.className = "class2";
     } else {
       element.className = "class1";
     }
  }
 </script>
</body>

</html>

Toggle the first time

Toggle the first time

Toggle the second time

Toggle the second time

That’s it.