How to convert a collection to an array in javascript

Copy it to a regular array?

var coll = document.getElementsByTagName('div');
var arr = [];
for(var i in coll) arr[i] = coll[i];

Been a while since I used JavaScript... you may need this instead:

var coll = document.getElementsByTagName('div');
var arr = [];
for(var i = 0; i < coll.length; i++) arr.push(coll[i]);

You can do this:

var coll = document.getElementsByTagName('div');

var arr = Array.prototype.slice.call( coll, 0 );

EDIT: As @Chris Nielsen noted, this fails in IE pre-9. Best would be to do some feature testing, and create a function that can handle either, or just do a loop as in the (second) solution from @brilliand.


This has become a lot simpler in modern browsers. I'll outline two approaches.

Spread operator

"Spread syntax allows an iterable (...) to be expanded"

const divs = document.getElementsByTagName('div');
const myArray = [...divs]; // [div, div, ...]

Array.from

Array.from "creates a new Array instance from an array-like or iterable object"

Example: Convert an HTML collection to array

const divs = document.getElementsByTagName('div');
const myArray = Array.from(divs); // [div, div, ...]