Tip: Create your own query selector shorthand

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"]');
Image credit: engin akyurt on Unsplash
Recommended snippets
Ever wanted to get the value of an HTML input element as a number? Learn an easy way to do it with this handy trick.
There are various ways to create an empty link, but some options are more appropriate than others. Learn the best way to handle empty links with this quick tip.
Increase your JavaScript code's performance when working with the DOM by leveraging this simple trick.