r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

1

u/wisepresident May 29 '19

getElementsBy.. returns a live collection

let divs = document.getElementsByTagName("div");

document.body.innerHTML = "";
console.log(divs);
-> HTMLCollection []

document.body.innerHTML = "<div></div>";
console.log(divs);
-> HTMLCollection [div]

No need to query again.

As such one might be inclined to remove classes like this, which won't work (as you are actively modifying the size of the array while you loop through it):

let divs = document.body.getElementsByClassName("myclass");

for(let i=0; i<divs.length; i++)
{
    divs[i].classList.remove("myclass");
}

You have to convert it to a non live collection:

let divs = new Array(...document.body.getElementsByClassName("myclass"));

for(let i=0; i<divs.length; i++)
{
    divs[i].classList.remove("myclass");
}