What is the return type of document.querySelectorAll

html, javascript

Solution

The type of the result is a NodeList. Since it is an Array-like object, you can run the `map`, `forEach` and other Array.prototype functions on it like this:

var result = document.querySelectorAll('a');
Array.prototype.map.call(result, function(t){ return t; })

The `map`, `forEach`, `any` and other functions in the Array prototype work on Array-like objects. For example, let's define an object literal with numerical indexes (0,1) and a length property:

var arrayLike = { '0': 'a', '1': 'b', length: 2};

The forEach method, applied to the `arrayLike` object will like on a real Array.

Array.prototype.forEach.call(arrayLike, function(x){ console.log(x) } ); //prints a and b

Problem

Let's say I have the following list: ``` <ol> <li>Cookies <ol> <li>Coffee</li> <li>Milk</li> <li class="test1">Chocolate </li> </ol> ``` and I perform this selection at the end of my html ``` var nodes = document.querySelectorAll('li:first-of-type'); ``` When I tried in Chrome `nodes.forEach` it gave me an error. When I looked at the value it looked like an array. I actually was able to navigate it using a regular for like: ``` for(var i=0;i<nodes.length;i++){ nodes[i].onclick= function(){ alert('Hello!'); }; } ``` So, what is the actual returned type of `document.querySelectorAll`? why array methods did not work? So, it looks like an array, can workaround it to make it work like an array but it is not an array?

Original source