5

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

3
  • var hello = document.getElementById('hello'); console.log(hello) Commented Jan 20, 2017 at 7:15
  • What exactly are you trying to do? Commented Jan 20, 2017 at 7:18
  • The method must know on which Document instance you want it to be called. Probably, it's document Commented Jan 20, 2017 at 7:20

2 Answers 2

8

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>

Sign up to request clarification or add additional context in comments.

1 Comment

::document.getElementById will be nice
3

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.