The GardenA blog by yours truly

The pauper鈥檚 jQuery

Black and white film still of a man in thought surrounded by grimy computer wiring
Pic loosely-related, from Darren Aronofsky鈥檚 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鈥檚 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鈥檚 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鈥檚 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 鈥淒OMContentLoaded鈥.

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

2 comments

  1. Xanthe says鈥
    2w8373gz the United Kingdom

    It doesn鈥檛 technically count towards my 鈥減osting about technology鈥 quota for 2024 if i post it at the very end of December 2023. 馃槈

  2. kyle says鈥
    Canada

    in a similar vein i always use

    function get(id) = document.getElementById(id)

Please be nice. Comments may be edited for proper spelling and capitalisation, because i鈥檓 a pedant. Basic formatting: *bold*, /italics/, [//satyrs.eu links]鈫 More