我正在尝试像这样遍历子节点:
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
但是,由于 forEach
函数,它会输出 Uncaught TypeError: undefined is not a function
。我也尝试使用 children
而不是 childNodes
但没有任何改变。
有人知道这是怎么回事吗?
最佳答案
变量 children
是一个 NodeList
实例和 NodeList
不正确 Array
因此他们不继承 forEach
方法。
还有一些浏览器实际上支持它nodeList.forEach
ES5
您可以使用 slice
从 Array
将 NodeList
转换为适当的 Array
。
var array = Array.prototype.slice.call(children);
您也可以简单地使用 call
调用 forEach
并将 NodeList
作为上下文传递给它。
[].forEach.call(children, function(child) {});
ES6
您可以使用 from
将 NodeList
转换为 Array
的方法。
var array = Array.from(children);
或者您也可以使用 spread syntax ...
像这样
let array = [ ...children ];
可以使用的 hack 是 NodeList.prototype.forEach = Array.prototype.forEach
然后您可以将 forEach
与任何 NodeList
一起使用> 无需每次都进行转换。
NodeList.prototype.forEach = Array.prototype.forEach
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
参见 A comprehensive dive into NodeLists, Arrays, converting NodeLists and understanding the DOM以获得很好的解释和其他方法。
关于javascript - 遍历子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24775725/