Home >Web Front-end >CSS Tutorial >Why Does getElementsByClassName() Only Change Every Other Class?
Unwanted Class Change Pattern: Every Other Class Affected
You are faced with a challenge while using getElementsByClassName() in JavaScript. When attempting to change the class of every element, you encounter an issue where only every other class is modified.
Root Cause: Modification of HTMLCollection
The underlying cause of this issue lies in the nature of the HTMLCollection returned by getElementsByClassName(). As you change the class of an element within the collection, the collection itself is updated and the element is no longer included. This means that as you iterate through the collection, you are effectively skipping alternate elements.
Solution: Iterate Through Array
To resolve this issue, you can iterate through an array of the original collection rather than modifying the collection as you proceed. This ensures that you apply the class change to every element, regardless of previous modifications.
Updated Code using For Loop:
var blockSet = document.getElementsByClassName("block-default"); var blockSetLength = blockSet.length; for (var i = 0; i < blockSetLength; i++) { blockSet[0].className = "block-selected"; }
Notes:
The above is the detailed content of Why Does getElementsByClassName() Only Change Every Other Class?. For more information, please follow other related articles on the PHP Chinese website!