Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign document.getElementById to variable in javascript [duplicate]

I think document.getElementById is a function.

So this function can be assigned to variable. Like this

var hello = document.getElementById;
console.log(hello('hello')));
<div id="hello">hello</div>

But It occurred error like this:

Uncaught TypeError: Illegal invocation

like image 556
khaki Avatar asked Dec 18 '22 10:12

khaki


2 Answers

The issue is context. When you take the reference to the function, you lose the function's context to document. So, in order to do what you are trying to, you need to bind the context:

var hello = document.getElementById.bind(document);

Working example:

var hello = document.getElementById.bind(document);
console.log(hello('hello'));
<div id="hello">hello</div>
like image 84
KevBot Avatar answered Dec 20 '22 22:12

KevBot


Wrap it as a function with a parameter which represents the ID.

var hello = function(id){
     return document.getElementById(id);
}
console.log( hello('hello')  );
<div id="hello">hello</div>
like image 35
Adam Azad Avatar answered Dec 20 '22 22:12

Adam Azad