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.
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 ...