Why is forEach not working for children?

后端 未结 5 1623
梦毁少年i
梦毁少年i 2020-12-14 00:36

I have a

with some child
in it. E.g.

&
5条回答
  •  囚心锁ツ
    2020-12-14 00:52

    Element.children is not an array. It is an object called an HTMLCollection. These do not have an array’s methods (though they do have the length property).

    To loop through it, you'll have to convert it into an array, which you can do using Array.prototype.slice:

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

提交回复
热议问题