8 ms·
> querySelectorAll returns an empty array if there are no matches, you don't need fancy string messages or errors for that. An empty NodeList[1] to be precise,
by atomwaffel 10y ago
> querySelectorAll returns an empty array if there are no matches, you don't need fancy string messages or errors for that.
An empty NodeList[1] to be precise, which is sort of kind of like an array in that it has a length property and you can access its elements with index notation (`nodeList[0]`), but it doesn't inherit from Array.prototype, so it doesn't support methods like `forEach` or `map`.
[1] https://developer.mozilla.org/en-US/docs/Web/API/NodeList https://developer.mozilla.org/en-US/docs/Web/API/NodeList
- maga 10y agoIndeed. Though still, NodeList has the length property with which you can check for "emptiness" the same as with an array, that's what I meant to say. Speaking of which, there are few features in ES2015 that make NodeList more palatable: 1. Iterables. NodeList is iterable and you can use, among others, the for..of construction to iterate over its content. 2. There is the Array.from method for turning array-like objects into true arrays. Not much different from our usual method of calling [].slice.call in this particular case, yet it's a bit shorter, standardized, and has a few additional perks, like accepting map function as the second argument.
- ycitm 10y agoAt least in new versions of Chrome, NodeList is iterable, so you can use forEach and map on it. https://medium.com/@devlucky/nodelist-object-is-finally-an-iterator-cc529d6e2490#.hef056iy9 https://medium.com/@devlucky/nodelist-object-is-finally-an-i...
- zackify 10y ago[ ...document.querySelectorAll('nodes') ] will convert it to a real array ;)