HTML Collections
HTML collections are array‑like objects returned by DOM methods such as document.getElementsByTagName(), document.getElementsByClassName(), and the children property. They are live collections: changes in the DOM are automatically reflected. They are not real arrays and have only a few methods (item, namedItem).
Key Points
Section titled “Key Points”- Live: updates automatically when DOM changes.
- Not real arrays; have a
lengthproperty but no array methods. - Convert to array using
Array.from()to work with array methods. - Also includes
NodeListfromquerySelectorAll(often static, not live).
Code Example
Section titled “Code Example”// Assume HTML has <div> elementsconst divs = document.getElementsByTagName("div");console.log(divs.length); // number of divsconsole.log(divs[0]); // first div
// Cannot use forEach directly on HTMLCollection// divs.forEach is undefined
// Convert to arrayconst divArray = Array.from(divs);divArray.forEach((div) => console.log(div));
// For NodeList (static)const items = document.querySelectorAll(".item");items.forEach((item) => console.log(item)); // works, but not live