6 ms·
This is how i've been doing it: const elements = document.querySelectorAll('li'); [...elements].forEach((element) => element.addEventListener('click', this
by ccheney 9y ago
This is how i've been doing it:
const elements = document.querySelectorAll('li');
[...elements].forEach((element) => element.addEventListener('click', this.onClickHandler));
- 52-6F-62 9y agoThis is a much more elegant solution. Thanks.
- loganfsmyth 9y agoIt's even easier now. `.forEach` on `NodeList` is standard https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach https://developer.mozilla.org/en-US/docs/Web/API/NodeList/fo..., so all you need to do is load a polyfill for that.
- shortstuffsushi 9y agoWhy do you need the [ ... elements ] -- can't you call foreach off elements directly? Is it not an array?
- humblebee 9y agoIt's not an array, but in recent versions of browser it does support `forEach` and some others. https://developer.mozilla.org/en-US/docs/Web/API/NodeList https://developer.mozilla.org/en-US/docs/Web/API/NodeList
- diggan 9y agoNo, it returns a NodeList, not an array. But, forEach exists on NodeList, but map and reduce does not (together with all the rest of the array functions).
- shortstuffsushi 9y agoHuh, TIL I guess. I've only barely messed with that, and it most have just been on "recent enough" versions to support array functions.
- Xcelerate 9y agoAnd this is why JavaScript is one of my least favorite languages. Is there a website that stays up-to-date with a brief summary of all this nonsense? I haven't programmed in JavaScript in 4 years but am needing to relearn it again for a project, and searching Google for "iterating over elements" in JavaScript returns 57 different techniques, all considered "the best way" at some different point in time over the last few years, and all with varying levels of browser support. Looping/filtering over things should just not be this convoluted of a process...
- shortstuffsushi 9y agoI think that the Mozilla Dev docs would probably be useful to you, or at least that's what I always end up going to -- https://developer.mozilla.org/en-US/ https://developer.mozilla.org/en-US/
- thibautg 9y agoIt makes sense because the DOM is like a huge global, mutable variable. Map and reduce are used in functional programming to create a new immutable variable. forEach allows to mutate each node from the nodeList.