How to change class for all elements retrieved by document.getElementsByClassName

getElementsByClassName, like other HTML collections, is “live”, that is, when you assign another class name to its member, it’s removed from the collection on the fly and its length gets decremented. That’s why your loop runs only once.

var x = document.getElementsByClassName('myClass');
alert("before: " + x.length);
x[0].className="otherClass";  
alert("after: " + x.length);
.myClass { color: black }
.otherClass { color: red }
<b class="myClass">hi</b>
<b class="myClass">hi</b>

Docs:

An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.


To answer in context to your question, you could set the className of the first element until there are none left in the collection:

while(x.length > 0) {
   x[0].className="otherClass";  
}

Leave a Comment