Tiny 274-byte Javascript DOM “Library”
Published on .
I make lots of webpages and occasionally add simple interactivity that rarely warrants including a full framework/library, but still I get sick of typing document.createElement('blah')
creating elements, so I use a tiny framework inspired by this comment.
It’s only 274 bytes and creates the following aliases:
$
aliased todocument.querySelector
$$
aliased todocument.querySelectorAll
$E
aliased todocument.createElement
with additional parameters for- Properties (object) to assign to the element (e.g.
{"classList": "foo"}
) - Children (list) to append to the element
- Properties (object) to assign to the element (e.g.
(Don’t forget that ParentNode.append()
can accept textNodes, so you can do $E("div",{}, ["foo"])
! Adios, document.createTextNode() ? )
const $ = document.querySelector.bind(document);const $$ = document.querySelectorAll.bind(document);function $E(t='div',p={},c=[]){let e=document.createElement(t);if(p.dataset){Object.assign(e.dataset,p.dataset);delete p.dataset} Object.assign(e,p);e.append(...c);return e;}
Code language: Python (python)
Keeping this handy has made me much less reluctant to add DOM nodes.
Caveat emptor, that too much of this and you’ll definitely end up with code that only you can read, but this is pretty safe since Chrome Dev Tools creates the $
and $$
aliases by default anyway.
I’m finding that these aliases, coupled with a few other modern Javascript-isms like fetch(
), Template Literals, arrow functions and async/await
, make it pretty fun and smooth to write.
P.S. Isn’t Object.assign()
great? That makes one line out of what used to require the following:
// New Way
Object.assign(obj, {"classList": "foo", "id": "bar")
// Old Way
obj.classList.add("foo")
obj.id = "bar"
Code language: Python (python)