How to toggle class
- Previous Page Toggle Text
- Next Page Add Class
Use JavaScript to toggle between adding and removing class names in elements.
Click the button to toggle the class name!
Toggle class
Step 1 - Add HTML:
After adding the class name to id="myDIV"
toggle between the div elements (in this example, we use a button to toggle the class name).
<button onclick="myFunction()">Try it</button> <div id="myDIV"> This is a DIV element. </div>
Step 2 - Add CSS:
Add a class name to toggle:
.mystyle { width: 100%; padding: 25px; background-color: coral; color: white; font-size: 25px; }
Step 3 - Add JavaScript:
obtain id="myDIV"
the <div> element, and in "mystyle"
Toggle classes between:
function myFunction() { var element = document.getElementById("myDIV"); element.classList.toggle("mystyle"); }
Related pages
Tutorial:How to Add Class
Tutorial:How to Remove Class
Reference Manual:HTML DOM Element classList Property
- Previous Page Toggle Text
- Next Page Add Class