javascript – Convert NodeList to Array  [ 60 views ]

Goal: work with nodeList as an array

The nodeList is great but sometime we need to convert it to an array for the easy processing.

old method

  var myNodeArray = Array.prototype.slice.call(document.querySelectorAll('div'));

old method – short form

  var myNodeArray = [].slice.call(document.querySelectorAll('div'));

ES6 way – shorter form

  var myNodeArray = Array.from(document.querySelectorAll('div'));

ES6 way – the shortest form

  var myNodeArray = [...document.querySelectorAll('div')];

enjoy…

One more thing is a little bit strange. Check the speed of the methods listed above.

var nodeList = document.querySelectorAll('*');
console.log('nodes: ' + nodeList.length);
console.time('t1'); var myArray1 = Array.prototype.slice.call(nodeList); console.timeEnd('t1');
console.time('t2'); var myArray2 = [].slice.call(nodeList); console.timeEnd('t2');
console.time('t3'); var myArray3 = Array.from(nodeList); console.timeEnd('t3');
console.time('t4'); var myArray4 = [...nodeList]; console.timeEnd('t4');

test like here – or where you want… – the result is something like this

nodes: 8720
t1: 13.525146484375ms
t2: 12.1533203125ms
t3: 18.273193359375ms
t4: 16.669921875ms
...
nodes: 8720
t1: 11.369140625ms
t2: 5.88623046875ms
t3: 14.56591796875ms
t4: 16.107666015625ms
...

Surprise, let’s try to explain the reason of the difference if you want. So if you work on a racket science project with a critical processing time – believe or not – than you should use only the second method, and just forget the funky solutions…

#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }