published: 19 Jul 2022
2 min read
How to toggle a CSS class of an element using JavaScript
The toggle()
method of the classList
property can be used to toggle a CSS class from an HTML element. This method takes in the class name as input, and toggle it.
If the class already exists in the element's classList
, it is removed. Otherwise, it adds it to the classList
.
Let us say you have got the following HTML element:
<div>🍕</div>
The following example demonstrates how you can add more olive
to the pizza
by using the toggle()
method:
const div = document.querySelector('div');
div.classList.toggle('olive');
The classList
property works in all modern browsers, and IE10 and above.
Take a look at this article to learn more about adding, removing, and toggling CSS classes in JavaScript.
![How to toggle a CSS class of an element using JavaScript | Coding Tips And Tricks How to toggle a CSS class of an element using JavaScript | Coding Tips And Tricks](/uploads/how-to-toggle-a-css-class-of-an-element-using-javascript.jpg)
Are we missing something? Help us improve this article. Reach out to us.
How to toggle a CSS class of an element using JavaScript
The toggle()
method of the classList
property can be used to toggle a CSS class from an HTML element. This method takes in the class name as input, and toggle it.
If the class already exists in the element's classList
, it is removed. Otherwise, it adds it to the classList
.
Let us say you have got the following HTML element:
<div>🍕</div>
The following example demonstrates how you can add more olive
to the pizza
by using the toggle()
method:
const div = document.querySelector('div');
div.classList.toggle('olive');
The classList
property works in all modern browsers, and IE10 and above.
Take a look at this article to learn more about adding, removing, and toggling CSS classes in JavaScript.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur