4 ms·
I use this: export const $ = document.querySelector.bind(document); export const $$ = document.querySelectorAll.bind(document); When using TypeScript
by emmanueloga_ 2y ago
I use this:
export const $ = document.querySelector.bind(document);
export const $$ = document.querySelectorAll.bind(document);
When using TypeScript the types for querySelectorAll are a bit hairy to map but by defining the consts like above the types "just work".
for (const tag of $$<HTMLParagraphElement>("p")) ...
I don't use Array.from in the result of $$ because sometimes creating an Array is not necessary. The NodeList returned can be iterated directly or converted to an array later if really needed:
[...$$("p")].map(p => ...)
Since I use TypeScript I lean on TSX for building HTML. I use preact's render-to-string package to convert it to a string [1].
---
1: https://github.com/preactjs/preact-render-to-string https://github.com/preactjs/preact-render-to-string
- cies 2y agoYou're a wizzard! JS keeps amazing me. It reminds me of Perl somehow. If Perl and Lua had a child, with some browsers APIs sprinkled on top.