Convert NodeList to array

后端 未结 4 1597
不知归路
不知归路 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:37

    If you're looking for a modern answer using ES6:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

    var nodes = document.querySelectorAll('div');
    nodes = Array.from(nodes);
    
    0 讨论(0)
  • 2021-01-12 03:49

    IE doesn't support NodeList in the standard way. This is why you should roll your own namespace and NOT extend browser core objects.

    You can do alert( typeof window.NodeList ) and see if it's undefined or not.

    0 讨论(0)
  • 2021-01-12 03:53

    First, don't use document.all -- it's non-standard and deprecated. Use document.getElementsByTagName to get the DIV elements in your case.

    Second, don't extend DOM objects such as NodeList -- built-in objects are a very strange breed and are not required to behave like any other objects that you generally work with. See this article for an in-depth explanation of this: What's wrong with extending the DOM.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题