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

ぐ巨炮叔叔 提交于 2019-12-06 05:13:14

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>

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!