published: 26 Mar 2022
2 min read
How to replace a CSS class of an element using 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:
<div>🍕</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.
Are we missing something? Help us improve this article. Reach out to us.
How to replace a CSS class of an element using 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:
<div>🍕</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.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur





