DEV Community

Eckehard
Eckehard

Posted on

getElementBy... ...destructuring

I've always wondered how verbose and cumbersome some very common web constructions are. One of this is getElementBy..., which is used as a central interface between Javascript and HTML

const myElement = document.getElementById("demo");
myElement.style.color = "red";
Enter fullscreen mode Exit fullscreen mode

This are 81 bytes pure text plus one constant in the global namespace, just to change a color. You can also write this as a oneLiner:

document.getElementById("demo").style.color = "red"
Enter fullscreen mode Exit fullscreen mode

still 52 bytes used.... You can also use

  • document.getElementsByClassName()
  • document.getElementsByName()
  • document.getElementsByTagName()

holy shit, what a waste of bandwidth.

Not only that the command is lengthy, it forces you to define an ID and a variable. And how do you know, that "myElement" and "demo" refer to the same element? Is this programming or a shell game? And - this is javascript used in a browser. You not only need to write it, each letter also has to be transferred over the internet. They could have used something smarter like DOM.ID(), which would reflect the tag you used for definition. But who cares.

I found a pretty nice solution to stop this waste of space: Use a Proxy!

getById = new Proxy(
    {},
    { 
      get: (_, tag) => {
        return document.getElementById(tag);
      },
    },
  );
Enter fullscreen mode Exit fullscreen mode

You can also write this as a oneLiner too:

getById = new Proxy({},{get:(_, tag)=>{return document.getElementById(tag);},},);
Enter fullscreen mode Exit fullscreen mode

Proxies are strange, but very helpful in this case. This is how you use it:

HTML:
<input id="filename"/>
<span class="chip-label">Search:</span>
<input id="search-input" placeholder="Suchen…" />
<button id="btn-search-prev" class="btn"></button>
Enter fullscreen mode Exit fullscreen mode
Javascript:
 const {filename, 
       "search-input":searchInput, 
       "btnSearch-prev": btnSearchPrev
       } = getById; 
Enter fullscreen mode Exit fullscreen mode

You can use the ID as a variable name, like "filename" above. But a name like "search-input" is not valid in Javascript, so the proxy allows renaming: "search-input":searchInput declares the renaming rule.

HTML ID´s are fixed, they do not change during program execution. So using getById is safe and maybe much better than spreading getElementBy... over your whole codebase.

Happy coding....

Top comments (0)