循环遍历childNodes [英] Loop through childNodes
问题描述
我正在尝试像这样循环遍历childNodes:
I'm trying to loop through childNodes like this:
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
但输出未捕获TypeError:undefined不是函数
由于 forEach
函数。我也尝试使用 children
而不是 childNodes
但没有改变。
However, it output Uncaught TypeError: undefined is not a function
due to forEach
function. I also try to use children
instead of childNodes
but nothing changed.
有人知道发生了什么吗?
Does anybody know what's going on?
推荐答案
变量 children
是 NodeList
实例, NodeList
s不正确 数组
因此他们不会继承 forEach
方法。
The variable children
is a NodeList
instance and NodeList
s are not true Array
and therefore they do not inherit the forEach
method.
此外一些浏览器实际上支持它 nodeList.forEach
Also some browsers actually support it nodeList.forEach
ES5
你可以使用 slice
从数组
转换 NodeList
到正确的数组
。
You can use slice
from Array
to convert the NodeList
into a proper Array
.
var array = Array.prototype.slice.call(children);
您也可以使用 致电
调用 forEach
并将 NodeList
作为上下文传递给它。
You could also simply use call
to invoke forEach
and pass it the NodeList
as context.
[ ] .forEach.call(children,function(child){});
ES6
您可以使用 from
方法将 NodeList
转换为数组
。
var array = Array.from(children);
或者您也可以使用传播语法 ...
喜欢这样
Or you can also use the spread syntax ...
like so
let array = [... children];
一个hack可以使用的是 NodeList.prototype.forEach = Array.prototype.forEach
然后您可以使用 forEach
NodeList
,无需每次都转换它们。
A hack that can be used is NodeList.prototype.forEach = Array.prototype.forEach
and you can then use forEach
with any NodeList
without having to convert them each time.
NodeList.prototype.forEach = Array.prototype.forEach
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
参见全面深入了解NodeLists,Arrays,转换NodeLists并了解DOM 很好的解释和其他方法。
See A comprehensive dive into NodeLists, Arrays, converting NodeLists and understanding the DOM for a good explanation and other ways to do it.
这篇关于循环遍历childNodes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!