How to Shorten document.getElementById in JavaScript

After you've been writing JavaScript for a while you'll eventually become aware that it's a real pain in the neck to keep on typing "document.getElementById". It takes time to type and, even if you're using some auto-complete editor feature, it still takes up visual space in your editor and also byte-space in your file. So, is there a better way? Sure there is; it's the same idea that you've probably seen in jQuery or similar libraries, with those mysterious $ signs everywhere.

How to Shorten "document.getElementById"

So, rather than typing out document.getElementById every time you need to access an element in the DOM, you can assign the document.getElementById method to a variable and then use that variable in your code.

For example, if you're currently using code like this:

const x = document.getElementById('element1');
const y = document.getElementById('element2');

(and where no doubt many more instances of document.getElementById are lurking), you could instead save a lot of time and effort by using something like this instead:

// this line goes at the top of your script or page
const $ = document.getElementById.bind(document);

and then you can access elements like this:

const x = $('element1'); 
const y = $('element2');

That's a lot easier, right? Especially if you're referring document.getElementById tens or even hundreds of times within a script.

Something more Readable?

Of course, you don't need to use the $ symbol on its own, which some people find confusing; you could also use a variable such as $mydoc, in which case your code would look like this:

const $mydoc = document.getElementById.bind(document);
const x = $mydoc('element1'); 
const y = $mydoc('element2');

You only need to assign the document.getElementById method to a variable a single time, and then it'll be usable throughout your script/page/project.

Shorten "document.querySelector"

Similarly, you could use similar code to shorten document.querySelector if you wished:

const $qs = document.querySelector.bind(document);
$qs("#demo").innerHTML = "Test";  // e.g. updating the innerHTML of an element

If you're using document.querySelector a lot in your script(s), you may find it easier to use the method shown. It not only saves some typing, but also makes the code clearer to read.

The Bottom Line ...

Anyway, that's the way you can shorten both document.getElementById and document.querySelector into something more succinct and manageable. Hopefully this method will save you some time as you're writing your JavaScript.