This post will illustrate the procedure to toggle the class using JavaScript.
How to Toggle the CSS Class Using Pure JavaScript in HTML?
For toggling classes using pure JavaScript, utilize the “toggle()” method of the “classList” attribute/property. The toggle() method accepts a class name as a parameter. Toggling a class means switching the presence of a class on an element in HTML. It involves checking if a class is present on an element, and if it is, removing it. If the class is not assigned to the element, it is added.
Example 1: Change the Color of the Element by Toggle Class Using Pure JavaScript in HTML
In the following example, we will change the background color of the button on the button click by toggling the class.
First, create a button, and assign an id “btn” to style the button. Attach an “onclick” event on it that will invoke the “classToggle()” function on the button click:
In the CSS file, create an id “btn” for styling the button:
padding: 3px;
margin: 2px;
font-family: sans-serif;
border-radius: .5rem;
}
Create a class named “yellow” to set the element’s background color:
background-color: yellow;
}
In JavaScript file, define a function “classToggle()” that will call the “toggle()” method of the “classList” property for toggling button class:
document.getElementById("btn").classList.toggle("yellow");
}
As you can see in the output while clicking on the button, the background color changes, it indicates that the “yellow” class has been successfully assigned to the button using the “toggle()” method of the “classList” property:
Example 2: Change the Font of the Element By Toggle Class Using Pure JavaScript in HTML
In the given example, we will toggle the CSS class for changing text on the button’s click event.
In an HTML file, create a <p> tag to show some text and a button. Assign an id “welcome” to the text that helps to get the text and assign a class using the toggle method:
<button id="btn" onclick="classToggle()">Click</button>
Create a CSS class “text” that will change the color and the font size of the text:
font-size: 30px;
color: #06b5f5;
}
Define a function “classToggle()” to assign the class “text” to the <p> tag element on the button click that will be retrieved using the assigned id with the help of “getElementById()” method.
document.getElementById("Welcome").classList.toggle("text");
}
It can be seen that the “text” class is assigned to the given text by clicking on the button:
We have provided all the essential instructions relevant to toggle the class using pure JavaScript in HTML.
Conclusion
To toggle the class using pure JavaScript in HTML, use the “toggle()” method of the “classList” property. It helps to assign a class to the element if it is assigned to it. This post illustrated the procedure for toggling classes using JavaScript.