Working as a web developer, you need to often add, remove, and toggle CSS classes based on the user interactions with elements on the web page.

Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically.
Toggle between adding and removing a class name from an element with JavaScript!
Example:
Step1.
Add HTML
Toggle between adding a class name to the div element with id=”myDIV” (in this example we use a button to toggle the class name).
<button onclick="myFunction()">Click me</button>
<div id="myDIV">
This is a DIV element.
</div>
Step2.
Add CSS
Add a class name to toggle:
.mystyle {
width: 100%;
padding: 25px;
background-color: lightblue;
color: red;
font-size: 25px;
}
Step3.
Add JavaScript
Get the <div> element with id=”myDIV” and toggle between the “mystyle” class:
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
}
Output:
This is a DIV element.
Enjoy coding!
Read also:
How to create the Comparison Slider?
CSS & JavaScript Bee Progress Bar