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

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

> Learn how to use the replace() method of the classList property to replace a CSS class of an element in JavaScript.

The `replace()` method of the `classList` property can replace a CSS class from an HTML element in JavaScript.

Let us say you have the following HTML element:

```javascript
<div class="pizza spicy hot crispy">?</div>
```

To replace the `spicy` class with the `olive` class, you can do the following:

```javascript
const div = document.querySelector('div')

div.classList.replace('spicy', 'olive')
```

The `replace()` method returns `true` if the class is successfully replaced with the new class. Otherwise, `false` is returned.

Unlike [add()](https://attacomsian.com/blog/javascript-dom-add-a-css-class-to-an-element), [remove()](https://attacomsian.com/blog/javascrpt-dom-remove-a-css-class-from-an-element), and [toggle()](https://attacomsian.com/blog/javascript-dom-toggle-a-css-class-of-an-element) methods of the `classList` property, the `replace()` method doesn't work in IE. You can only use it in modern browsers.

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.
