Home >Web Front-end >CSS Tutorial >Why Does getElementsByClassName() Only Change Every Other Class?

Why Does getElementsByClassName() Only Change Every Other Class?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 18:57:12223browse

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:

  • Instead of changing the class of each element individually, you can use a for loop to iterate through the elements and make the class change.
  • This updated code assigns the "block-selected" class to the first element of the blockSet array for each iteration.
  • By using an array, you avoid the issue of the collection being modified during iteration.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn