To replace a class of an element with a new one, you use the replace()
method of the classList
property of the element:
element.classList.replace(currentClass,newClass);
Code language: CSS (css)
Suppose you have a <div>
element as follows:
<div class="primary info">How to replace a class in JS</div>
Code language: JavaScript (javascript)
To replace the primary
class with the secondary
class, you use the following:
const div = document.querySelector('primary');
div.classList.replace('primary','secondary');
Code language: JavaScript (javascript)
Was this tutorial helpful ?