Nat TaylorBlog, Product Management & Tinkering

Tiny 274-byte Javascript DOM “Library”

Published on . Updated 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:

(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;}

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"

Popular Posts

Post Navigation

«
»