通过childNodes循环
我试图通过像这样的childNodes循环:
var children = element.childNodes; children.forEach(function(item){ console.log(item); });
但是,它输出Uncaught TypeError: undefined is not a function由于forEach函数, Uncaught TypeError: undefined is not a function函数。 我也尝试使用children而不是childNodes但没有任何改变。
有人知道发生了什么事吗?
variableschildren是一个NodeList实例,而NodeList不是真正的Array ,因此它们不会inheritanceforEach方法。
另外一些浏览器实际上支持它nodeList.forEach
ES5
您可以使用Array slice将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 ];
可以使用的破解是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); });
查看全面深入了解NodeLists,Arrays,转换NodeLists和理解DOM的一个很好的解释和其他方式来做到这一点。
这里是你如何使用for-in循环来做到这一点。
var children = element.childNodes; for(child in children){ console.log(children[child]); }
我对派对来说已经很晚了,但是由于element.lastChild.nextSibling === null ,下面这个对我来说似乎是最直接的select:
for(var child=element.firstChild; child!==null; child=child.nextSibling) { console.log(child); }
尝试使用for循环。 它在forEach给出错误,因为它是节点nodelist的集合。
或者这应该将节点列表转换为数组
function toArray(obj) { var array = []; for (var i = 0; i < obj.length; i++) { array[i] = obj[i]; } return array; }
或者你可以使用这个
var array = Array.prototype.slice.call(obj);
试试这个[逆序遍历]:
var childs = document.getElementById('parent').childNodes; var len = childs.length; if(len --) do { console.log('node: ', childs[len]); } while(len --);
或[按顺序遍历]
var childs = document.getElementById('parent').childNodes; var len = childs.length, i = -1; if(++i < len) do { console.log('node: ', childs[i]); } while(++i < len);
如果你做了很多这样的事情,那么为自己定义这个function可能是值得的。
if (typeof NodeList.prototype.forEach == "undefined"){ NodeList.prototype.forEach = function (cb){ for (var i=0; i < this.length; i++) { var node = this[i]; cb( node, i ); } }; }