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
2008-10-21 18:06:47
This made my day.
Joel Anair
2008-12-21 04:09:57
This doesn't work in IE
KooiInc
2009-02-13 09:04:05
This fails in IE6.
Heath Borders
2009-02-26 19:47:08
+2
A:
For a cross browser implementation I'd sugguest you look at prototype.js $A
function
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
2009-12-09 08:14:13