4 ms·
To use an example, I'd much rather do $(".elements").css("color", "red") versus var selector = document.getElementsByClassName('elements'); selector.style.c
by BlameKaneda 5y ago
To use an example, I'd much rather do
$(".elements").css("color", "red")
versus
var selector = document.getElementsByClassName('elements');
selector.style.color = 'red';
- lobstrosity420 5y agoYou can do const $ = document.querySelector; $('.elements').style.color = 'red'; Which is only marginally more verbose.
- yoz-y 5y agoNo you can't. $('.elements') in jQuery is more equivalent to querySelectorAll('.elements'). You can however do: document.querySelectorAll('a').forEach(a => a.style.color = 'red')
- MarkLowenstein 5y agoThis is the only post that I see so far that touches on the real innovation and unique value of jQuery: operating on groups. Everybody can go ahead and tell me that using a forEach every time is trivial, or that I can just insert some transpiler step in my build pipeline to take advantage of X language's convenient syntax, but the bottom line is that people use jQuery because it continues to be easier. Thank you for your insight and great design sense John Resig! Still not bested after 15 years.
- dspillett 5y agoThough your alias definition needs a little extra, or the function loses its context and colling it will just result ": const $ = document.querySelector.bind(document); or slightly less efficient, wrap in a function: const $ = function(x) { return document.querySelector(x) }; or if you want to be concise and don't need to support legacy IE: const $ = (x) => document.querySelector(x); (and as pointed out already, you need querySelectorAll() and a loop for what jQuery does by default, though your example will work for a single element)
- HelloNurse 5y agoThe jQuery example is good, but the "vanilla" example is cleaner and simpler: the class name isn't decorated with a dot, the CSS property name is not quoted, $ might be hijacked or overloaded, it is not obvious (compared to a plain assignment) that css is a setter and what arguments it takes.
- 1337shadow 5y agoSorry, that doesn't even work: > document.getElementsByClassName('comment').style > undefined You'd need a for loop right there I believe.