Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NodeList to array

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 recognized as valid:

NodeList.prototype.toArray = function() {
    var a = [];

    for (var i = 0, len = this.length; i < len; i++) {
        a[i] = this[i];
    }

    return a;
}

document.all.tags("div").toArray();

I tried adding a prototype function to an array just to check my sanity and it works correctly. That makes me think IE 8 doesn't actually return a NodeList? Here's a full example:

http://jsfiddle.net/e4RbH/

What am I doing wrong?

like image 793
Nelson Rothermel Avatar asked Dec 29 '10 21:12

Nelson Rothermel


2 Answers

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);
like image 170
Justin Noel Avatar answered Sep 21 '22 15:09

Justin Noel


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.

like image 37
Manngo Avatar answered Sep 19 '22 15:09

Manngo