use*_*771 67 javascript children loops
我正在尝试像这样循环遍历childNodes:
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
Run Code Online (Sandbox Code Playgroud)
但是,它Uncaught TypeError: undefined is not a function
由于forEach
功能而输出.我也尝试使用children
而不是childNodes
改变.
有人知道发生了什么吗?
Gil*_*esC 102
变量children
是一个NodeList
实例,而NodeList
s不是真的Array
,因此它们不会继承该forEach
方法.
也有一些浏览器实际上支持它 nodeList.forEach
ES5
您可以使用slice
from 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);
或者您也可以像这样使用扩展语法...
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);
});
Run Code Online (Sandbox Code Playgroud)
请参阅全面深入了解NodeLists,Arrays,转换NodeLists以及理解DOM以获得良好的解释和其他方法.
Emm*_*met 23
我参加派对的时间已经很晚了,但是从那以后element.lastChild.nextSibling === null
,以下似乎是我最直接的选择:
for(var child=element.firstChild; child!==null; child=child.nextSibling) {
console.log(child);
}
Run Code Online (Sandbox Code Playgroud)
Adi*_*rab 16
这是你如何用for-in
循环来做到这一点.
var children = element.childNodes;
for(child in children){
console.log(children[child]);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
const results = Array.from(myNodeList.values()).map(parser_item);
Run Code Online (Sandbox Code Playgroud)
NodeList 不是 Array 但 NodeList.values() 返回一个 Array Iterator,因此可以将其转换为 Array。
无法抗拒添加另一种方法,使用childElementCount
. 它从给定的父元素返回子元素节点的数量,因此您可以循环遍历它。
for(var i=0, len = parent.childElementCount ; i < len; ++i){
... do something with parent.children[i]
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
83644 次 |
最近记录: |