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:
<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 successfully replaced with the new class. Otherwise, false
is returned.
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.