変数childrenはNodeListインスタンスであり、NodeListsは真Arrayではないため、forEachメソッドを継承しません。
また、一部のブラウザは実際にそれをサポートしています nodeList.forEach
ES5
slicefromArrayを使用し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の理解に関する包括的な詳細を参照してください。