Object length changes obtained through document. Getelementsby * and document. Queryselectorall


Today, when dealing with a style modification, we plan to use js native method to select elements and modify their styles, and then use the following method

const active:HTMLCollectionOf<Element> = document.getElementsByClassName('is-active')
for (let i = 0; i < active.length; i++) {

Then it is found that the next element will always be left unmodified. After consulting MDN, it is found that htmlcollection is a timely object, which will be updated in time with other DOM modifications. The solution is to convert htmlcollection to array or use while loop. I will record both methods here, but I prefer to use the while loop, which is less written, and will not apply for additional memory.

const active:HTMLCollectionOf<Element> = document.getElementsByClassName('is-active')
const array:Element[] = Array.from(active)
for (let i = 0; i < array.length; i++) {


const active:HTMLCollectionOf<Element> = document.getElementsByClassName('is-active')
while (active.length){

Recommended Today

A thorough understanding of the hystrix go source code

Series articles: Usage and principle of hystrix go A thorough understanding of the hystrix go source code Opening The last article mainly introducedhystrix-goIn this article, let’s comprehensively analyze the source code. This article is very long. Please read it patiently. In addition, because the direct release of the source code affects the mobile phone reading […]