JS DOM: 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 DOM: Node, Node Type, Element
- JS DOM: Get Element by ID, Name, Class etc
- JS DOM: Get Element Parent, Child, Sibling
- JS DOM: NodeList vs HTMLCollection
- JS DOM: Iterate HTMLCollection
- JS DOM: Element Attribute Methods
- JS DOM: List, Add, Remove Class Attribute
- JS DOM: Create Element, Clone
- JS DOM: Insert, Remove, Replace Element
- JS DOM: Change Element Content
- JS DOM: Add, Remove Event Handler