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?
Although
NodeList
is not anArray
, it is possible to iterate over it withforEach()
. It can also be converted to a realArray
usingArray.from()
.However, some older browsers have not implemented
NodeList.forEach()
norArray.from()
. This can be circumvented by usingArray.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:
array.length
list.item(5) === list[5]
array.forEach
array.entries
array.values
array.keys