5 ms·
> Side benefit: also no weird $(thing)[0] when you need to use a DOM API, like HTML5 validity or whatever. But looping over querySelectorAll() is painful. I'm
by Carpetsmoker 8y ago
> Side benefit: also no weird $(thing)[0] when you need to use a DOM API, like HTML5 validity or whatever.
But looping over querySelectorAll() is painful. I'm not really a frontend dev, so perhaps I'm doing it wrong, but this is the "easier" way I found when I was writing an app a few weeks ago (in TypeScript):
// Get Array of HTMLElements from querySelectorAll().
let queryAll = (q: string): HTMLElement[] => {
let nodes = document.querySelectorAll(q);
let arr: HTMLElement[] = [];
arr.length = nodes.length;
for (let i = 0; i < nodes.length; i++) {
if (!(nodes[i] instanceof HTMLElement)) {
arr.length--;
continue;
}
arr[i] = nodes[i] as HTMLElement;
}
return arr;
};
- rmrfrmrf 8y agoreturn Array.from(document.querySelectorAll(q));
- Carpetsmoker 8y agoThis won't filter SVG elements, and unfortunately Array.from isn't available in IE (and perhaps some other browsers that are still in use).
- nicoburns 8y agolet queryAll = (q: string): HTMLElement[] => { let nodes = document.querySelectorAll(q); return Array.from(nodes).filter(node => (node instanceof HTMLElement)) as HTMLElement[]; } Will do the same. Note that `Array.from()` is a relatively new method, that you will need to polyfill if you wish to support internet explorer, but `Array.prototype.slice.call()` serves the same purpose and can be used in older browsers.
- nailer 8y ago> But looping over querySelectorAll() is painful. Not any more: let elements = document.querySelectorAll('.some-class') elements.forEach(function(element){ ... }) https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach https://developer.mozilla.org/en-US/docs/Web/API/NodeList/fo... PS. The other two answers here are outdated.
- runarberg 8y agoOr if you prefer: for (const element of document.querySelectorAll('.some-class')) { // ... }
- j79 8y ago> PS. The other two answers here are outdated. Sure, the other two answers may be "outdated" but they're still extremely useful if you're looking to calling map/filter/etc against your queried elements.
- runarberg 8y agoFor that you can write: const elements = document.querySelectorAll('.some-class'); const values = Array.prototype.map.call(elements, element => element.value); or more idiomatically (and perhaps a little slower): const elements = [...document.querySelectorAll('.some-class')]; const values = elements.map(element => element.value);
- nailer 8y agoThey asked about looping, not mapping or filtering.
- Carpetsmoker 8y agoI should have explained the use case better: I need to store an indexed array of elements for cache/querying later on; so forEach() isn't a good fit here. Other people suggested Array.from(), but that won't work in IE, and the polyfill for it is a lot longer/more complex than the for loop I wrote.
- mercer 8y ago[...document.querySelectorAll(el)]