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

Let us say you have the following HTML element:

<div class="pizza spicy hot crispy">🍕</div>

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

const div = document.querySelector('div');

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

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

Unlike add(), remove(), and toggle() 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 to learn more about adding, removing, and toggling CSS classes in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: