MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/javascript/comments/btxz72/what_are_some_javascript_things_beginners_dont/ep9d770/?context=3
r/javascript • u/[deleted] • May 28 '19
383 comments sorted by
View all comments
1
getElementsBy.. returns a live collection
getElementsBy..
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"); }
1
u/wisepresident May 29 '19
getElementsBy..returns a live collectionNo 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):
You have to convert it to a non live collection: