# How to toggle a CSS class of an element using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 13, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-toggle-a-css-class-of-an-element

> Learn how to toggle a CSS class of an HTML element by using the classList property of the element in 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](https://attacomsian.com/blog/javascrpt-dom-remove-a-css-class-from-an-element). Otherwise, it [adds](https://attacomsian.com/blog/javascript-dom-add-a-css-class-to-an-element) it to the `classList`.

Let us say you have got the following HTML element:

```javascript
<div class="pizza">?</div>
```

The following example demonstrates how you can add more `olive` to the `pizza` by using the `toggle()` method:

```javascript
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](https://attacomsian.com/blog/javascript-add-remove-toggle-css-classes) to learn more about adding, removing, and toggling CSS classes in JavaScript.
