The GardenDespatches from The Satyrs’ Forest

Posts tagged as “Javascript”

The pauper’s jQuery

Black and white film still of a man in thought surrounded by grimy computer wiring
Pic loosely-related, from Darren Aronofsky’s πJS makes me want to drill my brain out sometimes, too.

Javascript has come a long way since the days of marquee tags and spacer gifs. You can do a lot with the API they give you to mess around with your web page’s content — but alas, so many of the functions have such verbose names!

To solve this, while not having to deal with the heaving weight of jQuery’s ten billion lines of IE6 compatibility, i made my own little alternative, and carry it everywhere with me:

const $ = sel => document.querySelector(sel);
const $$ = sel => document.querySelectorAll(sel);

Element.prototype.$ = Element.prototype.querySelector;
Element.prototype.$$ = Element.prototype.querySelectorAll;

EventTarget.prototype.on = EventTarget.prototype.addEventListener;

const documentReady = fn => document.on("DOMContentLoaded", fn);

What it does, in a nutshell: Use $ to select something matching a CSS selector, and $$ to select an array of everything it matches. (This is already available in your browser’s dev tools!) You can also use it on an element to restrict your search to its children — say, $(".post").$$("aside"), or some other such fanciful chaining.

.on, meanwhile, lets you listen out for events like so: $("#my-button").on("click", () => { /* Your function here… */ })

Finally, documentReady is just a nicer name for the frankly obtuse “DOMContentLoaded”.

Enjoy. Or don’t, i suppose. Hopefully it makes your hypertext tinkering just a little nicer. :-)