Using document.getElementById() inside object, works in JSFiddle, TypeError in actual. Why?

余生颓废 提交于 2019-12-01 11:29:35

Because in JSFiddle your script is placed inside window.onLoad event handler by default. While in your case getElementById() method is unable to find not yet loaded element.

Put all your script right before closing </body> tag and it will work:

<script type="text/javascript">
    // ...
</script>
</body>

It works in Fiddle because of onLoad option specified here. The problem is that when new Composer line is fired, there's no such element in the DOM yet. Wrap this line in DOMReady handler - or move its invokation to the end of <body> element.

It's because your dom is not ready yet

function Composer(foobox) {
    this.foobox = document.getElementById(foobox);
    alert(this.foobox); --Prints null
    this.foobox.onkeydown = function(){window.alert("hello")};
}

Working code here. http://jsfiddle.net/LLUAB/1/

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