nas5w / javascript-tips-and-tidbits

A continuously-evolving compendium of javascript tips based on common areas of confusion or misunderstanding.
MIT License
1.2k stars 72 forks source link

Add Query Selector Shorthand Tip #8

Closed nas5w closed 5 years ago

nas5w commented 5 years ago

Add a "DOM Manipulation" section after the "Async Await" section. Make sure to add a link from the table of contents as well.

Add the following as the first item in the DOM Manipulation section.

Create Your Own Query Selector Shorthand

When working with JS in the browser, instead of writing document.querySelector()/document.querySelectorAll() multiple times, you could do the following thing:

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

// Usage
const demo = $("#demo");
// Select all the `a` tags
[...$$("a[href *='#']")].forEach(console.log)