Tip: Create your own query selector shorthand

Angelos Chalaris · JavaScript, Browser · Jun 12, 2021

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:

const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);

const mainContent = $('.main-content');
const externalLinks = $$('a[target="_blank"]');

Recommended snippets & collections

  • Tips & Tricks

    Snippet collection

    A collection of quick tips and tricks to level up your coding skills one step at a time.

  • Counter

    JavaScript, Browser

    Creates a counter with the specified range, step and duration for the specified selector.

  • Create HTML element

    JavaScript, Browser

    Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

  • URL parameters as object

    JavaScript, Browser

    Creates an object containing the parameters of the current URL.