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 const api = new Proxy({route: baseRoute}, handler); // handler is the microlib's export
const result = await api.get.some.route.invoke(); // GET {baseRoute}/some/route
invoke() is just how it finally fires the call. I didn't feel like spending too much time making it automatic, the benefits just weren't large enough to justify compared to just calling invoke().`api.some.route.get()`
<script>
document.addEventListener('DOMContentLoaded', () => {
window.thing.innerHTML = 'Hello, World!';
});
</script>
<div id="thing"></div> <div id="parent"></div>
Whoops.The native call does usually include a cache and will use it optimistically; however, the strategies around invalidating this cache are varied and some surprisingly basic DOM actions can trigger it. Then browsers usually fallback to the full DOM query case.
The cache eliminates this variability, which prior to flexbox, could be very useful in highly nested site designs particularly in mobile contexts.
Edit: My tone may have indicated that parent's solution was brittle. It's not!
The reason to have a separate system that correctly calls getElementById() is to avoid this issue.
So, it's actually a _less_ brittle mechanism that doesn't rely on legacy mechanisms and lacks the surprises that come with that.
But I do think the legacy browser behavior with the ID attribute as window properties is very brittle for the reasons you suggest
Reading it more slowly, I see it now, and, thank you!
Anyways.. Proxy is a wildly underappreciated and used class in JavaScript.