CKTIS / JavaScript
NodeList.forEach — iterating over nodes
NodeList.forEach calls a function for successive nodes in a DOM collection, passing the node, index, and collection.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
nodeList.forEach(callback[, thisArg])
callback(node, index, nodeList)NodeList.forEach, available as NodeList.prototype.forEach, calls callback(node, index, nodeList) in index order starting at zero. It returns undefined; callback results are ignored. The method supplies the optional thisArg as the this value for the callback call, but the callback need not see that exact value as this. An ordinary non-strict function substitutes its global this value for null or undefined and wraps other primitive values in objects. An arrow function uses this from its enclosing scope.
A NodeList is not an array. querySelectorAll() returns a static list, whereas childNodes is live and also includes text nodes. Avoid modifying a live collection during iteration.
This is a Web API, not a feature of a particular ECMAScript edition. Node 24 does not prove DOM support. In the target environment, check typeof nodes.forEach === 'function'.
Examples
const root = document.createElement('div');
for (const text of ['A', 'B']) {
const item = document.createElement('span');
item.textContent = text;
root.appendChild(item);
}
const nodes = root.querySelectorAll('span');
const lines = [];
nodes.forEach((node, index, list) => {
lines.push(`${index}:${node.textContent}:${list === nodes}`);
});
console.log(lines.join('\n'));Result
0:A:true 1:B:true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.