Hacker News new | ask | show | jobs
by collinmanderson 3107 days ago
Right, and that still doesn't handle applying the action to all _all_ items of that class.

It would need to be something like this, though it still doesn't automatically handle inline vs block:

document.querySelectorAll('.my-elements').forEach(function(el){el.style.display = 'block'})

And apparently there are issues even with that: https://css-tricks.com/snippets/javascript/loop-queryselecto...

2 comments

Ok, I kinda got sniped on this. Here's a first pass at a micro lib to do it using Proxy object:

    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));
        }
    })();

    // use like this:
    $('.my-elements').className = 'Important'; 
    $('.my-elements').style.color = 'Red';     
    $('.my-elements').classList.add('Another');
demo: https://codepen.io/anon/pen/RxGgNR
For reference, this is how you do this in jQuery: $('.my-elements').show()