html页面forEach用法,HTML DOM NodeList.forEach()用法及代码示例

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() Method

GeeksforGeeks

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);

},

);

}

输出:

单击按钮之前:

39d121d65f5494f5f3a6f31379773512.png

单击按钮后:使用forEach()调用元素。

aee643dae6e7eced2b4d6e77a908c426.png

在控制台中:可以看到元素值。

6d9d0f4d14d7105f8ac5d8d146425506.png

支持的浏览器:

谷歌浏览器

Edge

Firefox

Safari

Opera

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值