6 ms·
I'm trying to wean off of jQuery to reduce dependencies, but it makes me appreciate jQuery all the more. The native JS API is quite a bit more verbose and cumbe
by mschuetz 6y ago
I'm trying to wean off of jQuery to reduce dependencies, but it makes me appreciate jQuery all the more. The native JS API is quite a bit more verbose and cumbersome to use, and my absolute biggest gripe with it is that it doesn't even build on modern JS features. It's not compatible with for...of, map, filter, find, etc, which seems really strange for a relatively recent vanilla JS API.
Ironically, http://youmightnotneedjquery.com/ http://youmightnotneedjquery.com/ makes a pretty good case in favour of jQuery.
- megous 6y agoYou can easily extend NodeList.prototype with Array.prototype functions you like, and then just use them: ['map', 'find'].forEach(f => NodeList.prototype[f] = Array.prototype[f]); document.querySelectorAll('bla').map(el => whatever) That's what prototypes are for, anyway.
- rofrol 6y agoNice, ['map', 'find', 'filter', 'reduce'].forEach(f => NodeList.prototype[f] = Array.prototype[f]) // this is for for..of, cannot be above 'map', 'filter' etc. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator] document.querySelectorAll('span').map(el => console.log(el)) document.querySelectorAll('span').filter(el => el.className === 'fc-black-500').reduce((acc, el) => (acc += el.className, acc), '') for(let p of document.querySelectorAll('p')) { console.log(p) } - https://stackoverflow.com/questions/30836289/for-of-loop-queryselectorall https://stackoverflow.com/questions/30836289/for-of-loop-que...
- megous 6y agoYou can also create a getter on NodeList.prototype named '_' that returns Array.from(this) and then just use any of the array methods on it. Like document.querySelectorAll('div')._.some(...) So many options. :)
- bigfudge 6y agoWhat I don't understand is why the modern js api didn't just adopt query's conventions... they're so much nicer and more expressive most of the time.
- fendy3002 6y agoThey cannot. If they do and remove the old getelementbyname, etc, then it will be breaking change. If they just add $ notation, then there will be redundancy / inconsistency with existing api. Furthermore it will break / confuse apps which use jquery. Then it's far easier to just include minified jquery into your apps when you want to use it, and you have more control about it's version, etc.
- bigfudge 6y agoI'm not saying to use $, but the elegance/composability of jQuery could have been implemented as they updated the API. And deprecating getelementbyname etc could have been done over a long period.