Skip to content Skip to sidebar Skip to footer

How To Change All Classname Elements Of Specific Classname

How to change all classname elements of specific classname? I mean, let's say I have 3 divs with classes 'MyClass', and i want to change their classnames to 'notMyClass' in JavaScr

Solution 1:

Select all elements with the MyClass class with querySelectorAll, then loop through each element (with NodeList.forEach) and use classList.replace:

document.querySelectorAll('.MyClass').forEach(e => e.classList.replace('MyClass', 'notMyClass'))
.notMyClass{
  background-color:green;
}
<divclass="MyClass">A</div><divclass="MyClass">B</div><divclass="MyClass">C</div><!--TO--><divclass="notMyClass">D</div><divclass="notMyClass">E</div><divclass="notMyClass">F</div>

Solution 2:

Use querySelectorAll method:

Array.from(document.querySelectorAll('.MyClass')).forEach(elem => {
  elem.className = 'otherClass';
});

Note that I used Array.from, because querySelectorAll returns a NodeList, not an array.

Post a Comment for "How To Change All Classname Elements Of Specific Classname"