Friday, November 10, 2023

JavaScript: Generic selector proxied object

Lets create a thing to replace the very simple selector calls for id and classes.

First lets have simple selector for both the id and single class.

return document.getElementById(name) || 
    [...document.getElementsByClassName(name)]

Here we also return a single value when you pass an id and an array (expanding the default HTMLCollection) when a class is passed.

Now, if we want the make the whole thing more elegant like this:

elements.footer // == document.querySelector('#footer')
elements.button // == document.querySelectorAll('.button') 

We can use the a proxy handler to catch the selector like text that we defined above and return the elements.

const elements = new Proxy({}, {
    get(target, name) {
        return document.getElementById(name) || 
        	[...document.getElementsByClassName(name)];
    }
})

Where every time a property of elements must be deference the name of the property will end up in the get method in the name argument. 



_done