4 ms·
> But looping over querySelectorAll() is painful. Not any more: let elements = document.querySelectorAll('.some-class') elements.forEach(function(elem
by 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.