javascript - 遍历子节点

标签 javascript loops children

我正在尝试像这样遍历子节点:

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

您可以使用 sliceArrayNodeList 转换为适当的 Array

var array = Array.prototype.slice.call(children);

您也可以简单地使用 call调用 forEach 并将 NodeList 作为上下文传递给它。

[].forEach.call(children, function(child) {});


ES6

您可以使用 fromNodeList 转换为 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/

相关文章:

c - 在 C 语言中,带括号和不带括号的循环处理方式不同吗?

java - 使用 while 循环记分的问题 (Java)

html - 选择 :not selector 的 child 和 sibling

javascript - 使用 vuejs 为计算属性设置初始值

javascript - MVC 4 - 级联下拉列表 - Ajax JavaScript 调用问题

loops - 用于填充维度变量的隐式循环

javascript - 可调整大小的元素边框

kernel - 子级列表 - Sched.h - 内核

javascript - Bing map V8 - Uncaught ReferenceError : amd is not defined

java - 将 Javascript 数组转换为 Java 数组