49

その中に<div>子供<div>がいます。例えば

<div id="niceParent">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

で要素にアクセスできるので、配列forEachだと思ったので、関数でそれらをループしようとしましたdocument.getElementById("niceParent").children

console.log(document.getElementById("niceParent").children[1]);
console.log(document.getElementById("niceParent").children[2]);
console.log(document.getElementById("niceParent").children[3]);
console.log(document.getElementById("niceParent").children[4]);

したがって、私は試しました

document.getElementById("niceParent").children.forEach(function(entry) {
  console.log(entry);
});

これは機能していません。私は得る

TypeError: document.getElementById(...).children.forEach is not a function

回避策として、もっと複雑な <code>for..in ループでも試してみました。

for (var i in document.getElementById("niceParent").children) {
  if (document.getElementById("niceParent").children[i].nodeType == 1) console.log(document.getElementById("niceParent").children[i]);
}

期待どおりに機能しました。

なんで?

4

6 に答える 6

75

配列ではなく[MDN].childrenが含まれているためです。オブジェクトは配列のようなオブジェクトで、配列と同様にプロパティを公開し、数値プロパティを持ちますが、継承しないため配列ではありません。HTMLCollection HTMLCollection.lengthArray.prototype

次を使用して配列に変換できますArray.prototype.slice

var children = [].slice.call(document.getElementById(...).children);

ECMAScript 6では、イテレータと配列のようなオブジェクトを実際の配列に変換するための新しい API Array.from [MDN]が導入されています。意図がより明確になるため、可能であればそれを使用してください。

var children = Array.from(document.getElementById(...).children);
于 2013-02-26T17:00:50.500 に答える
12

Element.children配列ではありません。と呼ばれるオブジェクトHTMLCollectionです。これらには配列のメソッドがありません (lengthプロパティはありますが)。

それをループするには、それを配列に変換する必要があります。これは、次を使用して実行できますArray.prototype.slice

var children = Array.prototype.slice.call(document.getElementById("niceParent").children);

children.forEach(…);
于 2013-02-26T17:01:16.973 に答える
2

これを行うこともできます:

NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;

この後、コレクションで forEach を呼び出すことができます。

document.getElementById("niceParent").children.forEach(...)

最善かつ最も安全な方法は、実際には、まだ存在しない場合にのみ forEach を追加することです。

if (window.NodeList && !NodeList.prototype.forEach) {
   NodeList.prototype.forEach = Array.prototype.forEach;
}
if (window.HTMLCollection && !HTMLCollection.prototype.forEach) {
   HTMLCollection.prototype.forEach = Array.prototype.forEach;
}
于 2013-02-26T17:08:27.273 に答える