Home > Web Front-end > CSS Tutorial > Why Does Changing Class Names with `getElementsByClassName()` Affect Only Every Other Element in JavaScript?

Why Does Changing Class Names with `getElementsByClassName()` Affect Only Every Other Element in JavaScript?

Barbara Streisand
Release: 2024-11-28 06:42:17
Original
703 people have browsed it

Why Does Changing Class Names with `getElementsByClassName()` Affect Only Every Other Element in JavaScript?

className Changing Every Other Class Problem

Issue

In JavaScript, the getElementsByClassName() method returns an HTMLCollection containing elements that share a specified CSS class. However, it has been observed that when applying class changes to these elements, only alternate classes are affected.

Cause

This issue arises because the HTMLCollection returned by getElementsByClassName() is a live collection. This means that any changes to the DOM, such as modifying class names, will modify the collection itself.

As the className property is modified, the element is removed from the collection. This results in the size of the collection decreasing, and subsequent attempts to access the same element using its index may result in skipping alternate elements.

Solution

To resolve this issue, there are two potential solutions:

1. Modify Only the First Element's ClassName

Instead of iterating through the entire HTMLCollection and changing the className of each element, modify only the first element's className.

for (var i = 0; i < blockSetLength; i++) {
  blockSet[0].className = "block-selected";
}
Copy after login

2. Use a Static Array-like Data Structure

Instead of using getElementsByClassName(), which returns a live collection, create a static array-like data structure. This can be done by using the Array.from() function to convert the HTMLCollection to a regular array, or manually creating an array and filling it with the HTMLCollection elements.

const blockSetArray = Array.from(blockSet);

for (var i = 0; i < blockSetArray.length; i++) {
  blockSetArray[i].className = "block-selected";
}
Copy after login

The above is the detailed content of Why Does Changing Class Names with `getElementsByClassName()` Affect Only Every Other Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template