Thediv...
we will use className"/>Thediv...
we will use className">Home >Web Front-end >JS Tutorial >How to change an element's class using JavaScript?
The className attribute is used to change the class of an element. Here we will see two examples -
In this example, we will use the className attribute to change the class of the element. Let's say we have a div with class oldStyle -
<div id="mydiv" class="oldStyle"> <p>The div...</p> </div>
We will use the className attribute to set the above oldStyle class to a new class, i.e. newStyle -
function demoFunction() { document.getElementById("mydiv").className = "newStyle"; }
We achieved the above goal by calling demoFunction() by clicking the following button -
<p>Click the below button to change the class</p> <button onclick="demoFunction()">Change Class</button>
Let’s 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>
We can also create a button that works in both ways, that is, toggle. Clicking the button again switches 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>
The above is the detailed content of How to change an element's class using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!