JS: Iterate HTMLCollection
Iterate HTMLCollection or NodeList
For-Of Loop
for (let x of document.querySelectorAll("*")) x.style.color = "red";
Convert to Array
π WARNING: if convert to array, it is no longer Live Object
Array.from
Array.from(document.querySelectorAll("*"), (x) => { x.style.color = "red"; });
Spread Operator
[...document.querySelectorAll("*")].forEach((x) => { x.style.color = "red"; });
Live Object Converted to Array is Non-Live
// live object, once converted to array, does not reflect update let xx = document.getElementsByTagName("xx"); // returns a live HTMLCollection console.log(xx.length === 0); let x2 = Array.from(xx); // insert a xx tag into document body document.body.appendChild(document.createElement("xx")); // our selection of xx got updated console.log(xx.length === 1); // the converted array did not get update console.log(x2.length === 0);
Before JS2015
Before JS2015, HTMLCollection
is not iterable, nor NodeList
.
but they still are Array-Like Object.
Basic DOM Element Methods
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Get Element Parent, Child, Sibling
- DOM: NodeList vs HTMLCollection
- JS: Iterate HTMLCollection
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element Content
- JS: Add, Remove Event Handler