Search code examples
javascriptarraysnodelist

Proper way to treat NodeList as array?


Ok, so I know that the conventional wisdom of the "proper" way to use the results of a document.querySelectorAll (a NodeList) is to convert it to an array by using something like:

Array.prototype.slice.call(elements)

However, I have been experimenting with using them directly as array-like objects and it seems to work in structures such as:

document.querySelectorAll('selector').forEach(elem => console.log(elem.tagName));

My question is, are there unexpected consequences of using this much more convenient syntax?


Solution

  • Although NodeList is not an Array, it is possible to iterate over it with forEach(). It can also be converted to a real Array using Array.from().

    However, some older browsers have not implemented NodeList.forEach() nor Array.from(). This can be circumvented by using Array.prototype.forEach() — see this document's Example.

    --- https://developer.mozilla.org/en-US/docs/Web/API/NodeList

    All browsers except IE support all additional methods. Thus it is somewhat safe to use.

    NodeList implements:

    • [PROPERTY] length - Same as array.length
    • [METHOD] item - list.item(5) === list[5]
    • [METHOD] forEach - Same as array.forEach
    • [METHOD] entries - Same as array.entries
    • [METHOD] values - Same as array.values
    • [METHOD] keys - Same as array.keys