I have this webpage where I have to use a lot of document.getElementById
's. Since I am lazy, I thought of saving a few bytes by assigning document.getElementById
to a shorter variable:
var geid = document.getElementById;
However, this did not work as I intended. It gave me the following error:
Uncaught TypeError: Illegal invocation
Consider the following snippet which demonstrates my problem:
var foo = document.getElementById('foo');
console.log(foo); // outputs: '<div id="foo">Foo</div>'
var geid = document.getElementById;
var foo_geid = geid('foo'); // Aaaaaargh! Uncaught TypeError: Illegal invocation
console.log(foo_geid);
<div id="foo">Foo</div>
So what am I doing wrong? Why cannot I do what I did?
I checked "How does the "this" keyword work?", because I am having a hunch that this
has to do something with all this. (It feels to me like getElementById
got somehow detached from document
object). But I cannot really pinpoint and articulate the problem. Can anyone help me?