Is there any advantage to using querySelector()
vs jQuery's $()
in a userscript? I want the script to work in all major browsers that support userscripts, so I'm especially interested in cross-browser compatibility.
I started to wonder about this because I noticed honestbleeps' excellent Reddit Enhancement Suite includes jQuery as a dependency, but mostly sticks to querySelector()
for selecting elements and other basic JavaScript methods for DOM manipulation.
Is it just a matter of taste, or is there a reason to keep jQuery use to a minimum?
Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used.
The difference between querySelector() and querySelectorAll() is that querySelector() returns a single object with the first HTML element that matches the 'selectors', but querySelectorAll() returns an array of objects with all the HTML elements that match the 'selectors'.
The only reason to use querySelector()
or querySelectorAll()
is if you are not using jQuery. jQuery selectors are more powerful and more likely to perform consistently across browsers than advanced CSS selectors.
That said, including jQuery can needlessly complicate simple scripts. It requires Script Injection on most browsers -- which defeats sandboxes, creates potential conflicts, and makes your script dependent on a third-party server.
Here is a cross-browser way to include jQuery that minimizes conflicts. And, if the browser supports local jQuery copies, it doesn't require a third-party server to always be up/fast.
If the script is simple and you can avoid jQuery without much effort, use querySelector()
. Your script will work on all script-able browsers, 99+ percent of the time.
If the script loads jQuery anyway, use jQuery selectors for maximum power and consistency.
Note that for any but the most basic DOM manipulation, jQuery is usually worth the costs. And for Firefox+Greasemonkey or Chrome+Tampermonkey, there is almost no drawback to using jQuery if you @require
it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With