I've been using this for years: const $id = new Proxy({}, { // get element from cache, or from DOM get: (tgt, k, r) => (tgt[k] || ((r = document.getElementById(k)) && (tgt[k] = r))), // prevent programming errors set: () => $throw(`Attempt to overwrite id cache key!`) }); It's nice to be able to refer to elements by property name, so: Is reachable with: $id.thing And, since the underlying structure is just an object,…
You can use it like:
$('.my-elements').className = 'Important';
$('.my-elements').style.color = 'Red';
$('.my-elements').classList.add('Another');
const $ = (() => {
function listProxy(arr) {
return new Proxy(arr, {
set: (t, p, v, r) => {
for(let x of t) {
x[p] = v;
}
},
get: (t, p, r) => {
if(t.length > 0 && t[0][p] instanceof Function) {
return (...args) => { Array.prototype.map.call(t, (x) => x[p](args)) };
} else {
return listProxy( Array.prototype.map.call(t, (x) => x[p]) );
}
}
})
}
return (sel, root) => {
if(root === undefined) root = document;
return listProxy(root.querySelectorAll(sel));
}
})();
demo: https://codepen.io/anon/pen/RxGgNR