0

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 JavaScript, how to do it?

<div class="MyClass">
</div>
<div class="MyClass">
</div>
<div class="MyClass">
</div>

<!--TO-->

<div class="notMyClass">
</div>
<div class="notMyClass">
</div>
<div class="notMyClass">
</div>

I know that it's very easy by calling element by it's id, but how to do it by it's classname?

Eldzej02
  • 70
  • 1
  • 10
  • Strongly related: [How can I change an element's class with JavaScript?](/q/195951/4642212). Familiarize yourself with the [DOM API](//developer.mozilla.org/docs/Web/API/Document_Object_Model): [`querySelectorAll`](//developer.mozilla.org/docs/Web/API/Document/querySelectorAll), [`NodeList`](//developer.mozilla.org/docs/Web/API/NodeList), [`classList`](//developer.mozilla.org/docs/Web/API/Element/classList), [`DOMTokenList`](//developer.mozilla.org/docs/Web/API/DOMTokenList). Use [`Array.from`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/from). – Sebastian Simon Sep 19 '21 at 19:44

2 Answers2

3

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;
}
<div class="MyClass">A</div><div class="MyClass">B</div><div class="MyClass">C</div>

<!--TO-->

<div class="notMyClass">D</div><div class="notMyClass">E</div><div class="notMyClass">F</div>
Spectric
  • 30,714
  • 6
  • 20
  • 43
-1

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.

Furman
  • 2,017
  • 3
  • 25
  • 43
  • [`NodeList.prototype.forEach`](//developer.mozilla.org/docs/Web/API/NodeList/forEach) can be used here. – Sebastian Simon Sep 19 '21 at 19:46
  • 1
    **Stop using `className`** unless you're creating a brand new Element from in-memory. Use what's best: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList – Roko C. Buljan Sep 19 '21 at 19:47