views:

2295

answers:

2

Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?

+10  A: 
var arr = Array.prototype.slice.call( htmlCollection )

will have the same effect using "native" code.

harpo
This made my day.
Joel Anair
This doesn't work in IE
KooiInc
This fails in IE6.
Heath Borders
+2  A: 

For a cross browser implementation I'd sugguest you look at prototype.js $A function

copyed from 1.6.1:

function $A(iterable) {
  if (!iterable) return [];
  if ('toArray' in Object(iterable)) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

It doesn't use Array.prototype.slice probably because it isn't available on every browser. I'm afraid the performance is pretty bad as there a the fall back is a javascript loop over the iterable.

Gareth Davis