Javascript Shorthand for getElementById

Viewed 38495

Is there any shorthand for the JavaScript document.getElementById? Or is there any way I can define one? It gets repetitive retyping that over and over.

23 Answers

Another wrapper:

const IDS = new Proxy({}, { 
    get: function(target, id) {
        return document.getElementById(id); } });

IDS.camelCaseId.style.color = 'red';
IDS['dash-id'].style.color = 'blue';
<div id="camelCaseId">div 1</div>
<div id="dash-id">div 2</div>

This, in case you don't want to use the unthinkable, see above.

You can use a wrapper function like :

const byId = (id) => document.getElementById(id);

Or

Assign document.getElementById to a variable by binding it with document object.

const byId = document.getElementById.bind(document);

Note: In second approach, If you don't bind document.getElementById with document you'll get error :

Uncaught TypeError: Illegal invocation

What Function.bind does is it creates a new function with its this keyword set to value that you provide as argument to Function.bind.

Read docs for Function.bind

const $id = id => document.getElementById(id);
...
$id('header')

I just use: function id(id) {return document.getElementById(id);}", called by id(target id).action; It works for me in Chrome, Edge & Firefox, though not in Safari or Opera.

Related