Home >Web Front-end >CSS Tutorial >Why Does getElementsByClassName() Only Change Every Other Element\'s Class?
ClassName Issue with HTMLCollection
In your JavaScript code, you're using getElementsByClassName() to select elements with the class "block-default." However, as you've noticed, the class changes only for every other element.
The problem lies in the nature of the HTMLCollection returned by getElementsByClassName(). It's a live collection that reflects the current state of the DOM. When you change the class name of an element, it's removed from the collection, making it unavailable for further selection.
Solution: Iterative Approach
To solve this issue, you can iterate through the HTMLCollection and change the class name of each element individually. By doing so, you'll ensure that every element receives the updated class:
var blockSet = document.getElementsByClassName("block-default"); var blockSetLength = blockSet.length; for (var i = 0; i < blockSetLength; i++) { blockSet[i].className = "block-selected"; }
Alternate Solution: Only Change the First Element
Alternatively, you can modify the first element's class name, as it remains in the collection even after its class changes. Here's the modified code:
for (var i = 0; i < blockSetLength; i++) { blockSet[0].className = "block-selected"; }
This way, you only need to update the class name of the first element, and the HTMLCollection will still contain all the elements with the "block-selected" class.
Note: Iterating through the elements is a better solution for practical scenarios where many elements may be returned by getElementsByClassName() and you need to perform operations on all of them.
The above is the detailed content of Why Does getElementsByClassName() Only Change Every Other Element\'s Class?. For more information, please follow other related articles on the PHP Chinese website!