Why is forEach not working for children?

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

I have a

with some child
in it. E.g.

&
5条回答
  •  悲&欢浪女
    2020-12-14 01:05

    You can also do this:

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

    And after this you can call forEach on your collection:

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

    The best and most secure way would be actually to only add forEach in cases when it doesn't already exist:

    if (window.NodeList && !NodeList.prototype.forEach) {
       NodeList.prototype.forEach = Array.prototype.forEach;
    }
    if (window.HTMLCollection && !HTMLCollection.prototype.forEach) {
       HTMLCollection.prototype.forEach = Array.prototype.forEach;
    }
    

提交回复
热议问题