How to toggle between two classes in JavaScript
If you're thinking to implement the dark/light feature into your web page, you must know how to toggle between two classes.
Well, we will try to understand with an example. Suppose we have a div element with background color blue and text color red.
Example :
<style>
.my_div{
background-color: blue;
color:red;
}
<style>
<div class="my_div">
This is a div element .
</div>
Now we need to create a new class with black as background color and white as text color.
Example :
<style>
.new_class{
background-color: black;
color:white;
}
</style>
Then, we will create a button and whenever this button is clicked, a function is involved.
Example:
<button onclick="myFunc()"> Change Class </button>
Finally, we have to create the function and using the toggle() method , we can add or remove the new class.
For example, the toggle() method adds the new_class to the div element if it doesn't have it, or remove it if it does. Well, but I didn't understand.
For example, we want to add the class to the element when we click the button, and remove the class when we click the button again.
<style>
.my_div{
background-color: blue;
color:red;
}
.new_class{
background-color: black;
color:white;
}
</style>
<div class="my_div">
This is a div element .
</div>
<button onclick="myFunc()">Toggle Class</button>
<script>
function myFunc(){
document.querySelector('.my_div').classList.toggle('new_class');
}
</script>
Try it Yourself »
