5 ms·
Just yesterday I spent 4 hours looking for something that'd let me use DOM queries with map and forEach. I settled on NodeList.js. I didn't want JQuery or Zepto
by macawfish 10y ago
Just yesterday I spent 4 hours looking for something that'd let me use DOM queries with map and forEach. I settled on NodeList.js. I didn't want JQuery or Zepto or anything larger than 1 KB, but I also didn't want to write something to do this, something I'd have to copy and paste into the next project.
- Scottopherson 10y agoIf you happen to be using ES6 you can utilize `Array.from` to turn node lists into arrays: let nodes = Array.from(document.querySelectorAll('.item')); nodes.forEach(node => console.log(node)); https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- macawfish 10y agoThat's not so bad. Thanks for the tip!
- coltonv 10y agoNot sure why you spent 4 hours on that, in addition to the other response there's also this method, which lets you call map on it and also call all the methods available to NodeList (you'd lose access to those if you converted it to an array) var classNames = [].map.call(nodeList, (entry) => entry.className) The 'call' function in java script allows you to specify the "this" in the calling of the function. So we grab the map function from an empty array, and call it with nodeList as "this". You can find out more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... You could also use that to make a super simple method to allow you to call map on any array like object, then you can import this into your other files: function map(arr, callback) { return Array.prototype.map.call(arr, callback); } Then call it like var classNames = map(nodeList, (node) => node.className);
- macawfish 10y agoWell, I spent four hours on it because I was also considering the other fancy features of these libraries and playing with them. Which is why this post made me think of yesterday's four hour fancy javascript helper library exploration session.
- msoad 10y agoforEach is coming to DOMNodeList plus DOMNodeList is an iterable and you should be using for..of to iterate in them. There is also Array.from that others mentioned