HTML DOM NodeList forEach() 方法

定义和用法

forEach() 方法为 NodeList 中的每个节点执行回调函数。

实例

例子 1

为文档的每个子节点执行函数:

const list = document.body.childNodes;

list.forEach(
  function(node, index) {
    text += index + " " + node;
  }
);

亲自试一试

例子 2

列出文档子节点的名称:

const list = document.body.childNodes;

list.forEach(
  function(node) {
    text += node.nodeName;
  }
);

亲自试一试

例子 3

列出文档子节点的类型:

const list = document.body.childNodes;

list.forEach(
  function(node) {
    text += node.nodeType;
  }
);

亲自试一试

语法

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

参数

参数描述
function()必需。为每个节点运行的函数。
currentValue必需。当前节点的值。
index可选。当前节点的索引。
arr可选。当前节点的 NodeList。
thisValue

可选。默认 undefined。

作为其 this 值传递给函数的值。

返回值

无。

浏览器支持

nodelist.forEach() 是 DOM Level 4 (2015) 特性。

所有现代浏览器都支持它:

ChromeEdgeFirefoxSafariOpera
ChromeEdgeFirefoxSafariOpera
支持支持支持支持支持

Internet Explorer 11(或更早版本)不支持 nodelist.forEach()。

相关页面

length 属性

entries() 方法

item() 方法

keys() 方法

values() 方法

NodeList 对象

childNodes() 方法

querySelectorAll() 方法

getElementsByName() 方法