How to change an element's class with JavaScript?


The className property is used to change an element’s class. Here, we will see two examples −

  • How to change the element’s class using className property.
  • How to toggle between old and new classes.

Change the element’s class using className property

In this example, we will change the class of an element using the className property. Let’s say we have a div with class oldStyle −

<div id="mydiv" class="oldStyle">
   <p>The div...</p>
</div> 

We will set the above oldStyle class to a new class i.e. newStyle using the className property −

function demoFunction() {
   document.getElementById("mydiv").className = "newStyle";
} 

We have achieved the above by calling the demoFunction() on the click of the following button −

<p>Click the below button to change the class</p>
<button onclick="demoFunction()">Change Class</button>

Example

Let us see the complete example −

<!DOCTYPE html> <html> <style> .oldStyle { background-color: yellow; padding: 5px; border: 2px solid orange; font-size: 15px; } .newStyle { background-color: green; text-align: center; font-size: 25px; padding: 7px; } </style> <body> <h1>Changing the class</h1> <p>Click the below button to change the class</p> <button onclick="demoFunction()">Change Class</button> <div id="mydiv" class="oldStyle"> <p>The div...</p> </div> <script> function demoFunction() { document.getElementById("mydiv").className = "newStyle"; } </script> </body> </html>

Toggle between new and old classes

Example

We can also create a button that work for both ways i.e. toggle. Click of a button again will toggle it back −

<!DOCTYPE html> <html> <style> .oldStyle { background-color: yellow; padding: 5px; border: 2px solid orange; font-size: 15px; } .newStyle { background-color: green; text-align: center; font-size: 25px; padding: 7px; } </style> <body> <h1>Toggle the class</h1> <p>Click the below button to toggle the classes</p> <button onclick="demoFunction()">Toggle Class</button> <div id="mydiv" class="oldStyle"> <p>The div...</p> </div> <script> function demoFunction() { const element = document.getElementById("mydiv"); if (element.className == "oldStyle") { element.className = "newStyle"; } else { element.className = "oldStyle"; } } </script> </body> </html>

Updated on: 18-Oct-2022

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements