Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created October 1, 2021 05:11
Show Gist options
  • Save gtchakama/ab3c88d15ff4b0a3c7d39e8189a82c56 to your computer and use it in GitHub Desktop.
Save gtchakama/ab3c88d15ff4b0a3c7d39e8189a82c56 to your computer and use it in GitHub Desktop.
Query selector shorthand
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
const mainContent = $('.main-content');
const externalLinks = $$('a[target="_blank"]');
@gtchakama
Copy link
Author

Most of us are familiar with jquery and probably quite a few of us are familiar with the Chrome console's $ and $$ shorthands for query selectors.

I recently figured out a way to replicate these shorthands in my code, using Document.querySelector(), Document.querySelectorAll() and Function.prototype.bind(). Here's how to do it, just make sure you don't mix them up with jquery if you are still using it:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment