Reputation: 23
There is a frequent use of document.getElementById() in my code . so is there any way to abbreviate this long line of code to a small variable , if possible?
Upvotes: 0
Views: 34
Reputation: 1628
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
Upvotes: 1