JS: Iterate HTML Elements
Iterate HTMLCollection or NodeList
DOM get elements methods
return either
HTMLCollection
or
NodeList
,
both are
Iterable Object,
since JS2015.
Use for-of Loop.
for (let x of document.querySelectorAll("*")) x.style.color = "red";
or use Spread Operator to turn it to array.
[...document.querySelectorAll("*")].forEach((x) => { x.style.color = "red"; });
or use JS: Array.from to turn it into array.
Array.from(document.querySelectorAll("*")).forEach((x) => { x.style.color = "red"; });
Before JS2015
For before JS2015 code,
HTMLCollection
and
NodeList
are not iterable,
but still are
Array-Like Object.
see
Apply Array Method to Array-Like Object
Basic DOM Element Methods
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Iterate HTML Elements
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Get Element Parent, Child, Sibling, Navigate DOM Tree
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element's Content
- JS: Add, Remove Event Handler