NodeList接口的forEach()方法按插入顺序为列表中的每个值对调用一次在参数中给定的回调。
用法:
NodeList.forEach(callback, currentValue);
参数:
Callback:在NodeList的每个元素上执行的功能。它接受3个参数:
currentValue:NodeList中要处理的当前元素。
currentIndex (Optional):NodeList中正在处理的currentValue的索引。
listobj (Optional):应用了forEach()的NodeList。
thisArg (Optional):执行回调时用作此值。
返回值:此方法返回未定义。
例:在此示例中,我们将创建一个NodeList,因此将使用此方法从NodeList中获取所有值。
HTML | DOM NodeList.forEach() MethodGeeksforGeeks
HTML | DOM NodeList.forEach() Method
Click Here
var a = document.getElementById("a");
a.innerHTML = "elements are:"
function Geeks(){
var parentNode = document.createElement("div");
var c1 = document.createElement("p");
var c2 = document.createElement("span");
var c3 = document.createElement("h1");
parentNode.appendChild(c1);
parentNode.appendChild(c2);
parentNode.appendChild(c3);
var nodelist = parentNode.childNodes;
nodelist.forEach(
function(currentValue, currentIndex, listObj) {
a.innerHTML += "
"+currentValue.localName + ``;console.log(currentValue, currentIndex);
},
);
}
输出:
单击按钮之前:
单击按钮后:使用forEach()调用元素。
在控制台中:可以看到元素值。
支持的浏览器:
谷歌浏览器
Edge
Firefox
Safari
Opera