HTML DOM NodeList forEach() Method

定义和用法

Definition and Usage

The forEach() method executes a callback function for each node in the NodeList.

Example

Example 1

const list = document.body.childNodes;
list.forEach(
  Execute a function for each child node of the document:
    function(node, index) {
  }
);

Try It Yourself

text += index + " " + node;

Example 2

const list = document.body.childNodes;
list.forEach(
  function(node) {
    List the names of document child nodes:
  }
);

Try It Yourself

Example 3

List the types of document child nodes:

const list = document.body.childNodes;
list.forEach(
  function(node) {
    text += node.nodeType;
  }
);

Try It Yourself

Syntax

nodelist.forEach(function(currentValue, index, arr) thisValue)

Parameters

Parameters Description
function() Required. The function to be executed for each node.
currentValue Required. The value of the current node.
index Optional. The index of the current node.
arr Optional. The NodeList of the current node.
thisValue

Optional. Default undefined.

The value passed to the function as its this value.

Return Value

None.

Browser Support

nodelist.forEach() is a DOM Level 4 (2015) feature.

All modern browsers support it:

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Support Support Support Support Support

Internet Explorer 11 (or earlier versions) does not support nodelist.forEach().

Related Pages

length Property

entries() Method

item() Method

keys() Method

values() Method

NodeList Object

childNodes() Method

querySelectorAll() Method

getElementsByName() Method