Convert NodeList to array

后端 未结 4 1596
不知归路
不知归路 2021-01-12 03:25

I\'m having a hard time converting a NodeList to an array in IE 8. The following works perfectly in Chrome, but in IE 8 toArray() is not recognize

4条回答
  •  醉梦人生
    2021-01-12 03:57

    Old question, but here is a tried & true method:

    var nodes=document.querySelectorAll("div"); //  returns a node list
    nodes=Array.prototype.slice.call(nodes);    //  copies to an array
    

    Explanation

    • document.querySelectorAll uses a CSS-style selector to find elements and returns a node list. It works as of IE 8.
    • The slice method copies a portion of an array-like collection (in this case all of it) into a new array.
    • call allows you to borrow a method from one object to use on another

    To find the node list you could also have used `document.getElementsByTagName(), but this one is more flexible.

提交回复
热议问题