toArray() method for array-like DOM list objects

It would be nice to add toArray() method to all array-like DOM list objects, e.g. DOMNodeList and DOMTokenList.

DOMNodeList is returned, for example, by document.getElementsByTagName() and element.querySelectorAll() methods.
DOMTokenList is returned, for example, by element.classList property.

Converting DOM list to Array is often used in real-world JavaScript applications.

Currently, two ways for this purpose are used most widely:

1. Array.prototype.slice.call(domList, 0);
2. full manual iterating trough DOM list and adding items one by one to an array.

First way seems to be a hack, second one is just slow as any pure-script iterating is.

Introducing _native_ toArray() method would be multiple times faster than pure-script solutions and thus would hugely speedup the whole Web.

Example for additional clarity:

assuming a document with two DIV elements (<div></div>), following call:
document.getElementsByTagName('div').toArray()

would return Array object with two DIV elements as Array items.

Thanks.

Received on Thursday, 22 December 2011 18:19:35 UTC