How to toggle a CSS class of an element using JavaScript

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

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming