Files
30-seconds-of-code/blog_posts/javascript-query-selector-shorthand.md
2022-03-21 15:54:40 +02:00

1006 B

title, shortTitle, type, tags, expertise, author, cover, excerpt, firstSeen, lastUpdated
title shortTitle type tags expertise author cover excerpt firstSeen lastUpdated
Tip: Create your own query selector shorthand Query selector shorthand tip javascript,browser intermediate chalarangelo blog_images/pineapple-at-work.jpg Ever wanted to create your own jquery-like query selector shorthand? Here's how! 2021-02-08T11:00:00+02:00 2021-06-12T19:30:41+03:00

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"]');