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. :-)
It doesn’t technically count towards my “posting about technology” quota for 2024 if i post it at the very end of December 2023. 😉
in a similar vein i always use
function get(id) = document.getElementById(id)