3 ms·
Thought this was a clever trick: const $ = _ => document.querySelector(_) Pretty well sums up the state of jQuery in 2019 (almost 2020!)
by lwb 7y ago
Thought this was a clever trick:
const $ = _ => document.querySelector(_)
Pretty well sums up the state of jQuery in 2019 (almost 2020!)
- drusepth 7y agoWhat does this trick do?
- grardb 7y agoWritten in older JS, it would look like this: $ = function(_) { return document.querySelector(_) } It basically turns `$` into an alias for `document.querySelector`. I'm not sure that it's any different from: $ = document.querySelector
- iudqnolq 7y agoSadly it is different because of the magic of this. If you set something equal to document.querySelector and then call it this will no longer refer to document. There are fancier ways with Function.prototype.bind, but wrapping in a function is the easiest conceptually. https://www.taniarascia.com/this-bind-call-apply-javascript/ https://www.taniarascia.com/this-bind-call-apply-javascript/ For this specific case, you can see this at https://stackoverflow.com/q/13383886/8334056 https://stackoverflow.com/q/13383886/8334056
- andai 7y agoJust checked on CanIUse, querySelector() actually has full support* since 2009! Btw, querySelectorAll() to match multiple elements. * IE partial until 2011
- mkoryak 7y agoThis is written by someone who has never used jquery or forgot it. The beauty of jquery was not being able to use CSS selectors to find elements, but in being able to work with multiple selected elements as if it was a single one. Ok, you will say, but you can always do [... document.querySelectorAll('.foo .bar')].map(it => it.style.backgroundColor = 'corn'); instead of $('.foo .bar').css('backgroundColor', 'corn'); and it is clearly better because it does not use jQuery. Don't get me wrong, jQuery has many issues that make it a very poor choice for big modern web applications, but please don't tell me that it can be replaced by querySelectorAll.
- rkuykendall-com 7y agoNa, the beauty of jQ was writing JS once and being confident most of it would work in most browsers. Everything else was sugar.
- lwb 7y ago> please don't tell me that [jQuery] can be replaced by querySelectorAll. I didn't, and it can't -- my comment was merely to suggest that jQuery is now a shell of its old self, thanks largely to the improvement of browser DOM APIs.
- danlugo92 7y agofor (const node of document.querySelectorAll('.foo .bar')) { node.backgroundColor = 'corn' }
- ZeikJT 7y agoNot sure why someone would use map like that (which would unnecessarily generate and return a new array of 'corn's) instead of just forEach. I'd also probably recommend using Array.from instead of a spread (for clarity) but less concerned about that part.
- quickthrower2 7y agoHmm. Usually underscore as a function parameter should mean unused variable. Ok maybe I am too much of a fusspot.