`getElementById` returning null [duplicate]

做~自己de王妃 提交于 2019-12-02 20:19:16

问题


A case of document.getElementById returning null. I've read four other questions in SO, and read the reference on MDN, but I have no clue of what's wrong; please help me. Code is as follows:

HTML

<button id="btnButton1">Button1!</button><br>
<button id="btnButton2">Button2!</button><br>
<span id="spanOutPut"></span>

Javascript

getBYid = function(elem) {
    return document.getElementById(elem); }

funButton1 = function() { getBYid('spanOutPut').innerHTML = "Button 1 pressed!!" };
funButton2 = function() { getBYid('spanOutPut').innerHTML = "Did you press the Button 2?!" };

getBYid("btnButton1").addEventListener('click', funButton1, false);
getBYid("btnButton2").addEventListener('click', funButton2, false);

I get a TypeError: getBYid(...) is null, on FireBug.

It works when I simply remove the calls to addEventListener from the JS and set onclick inline, as in the following code:

<button onclick="funButton1()">Button1"</button>

What is the difference?


回答1:


You have to put this after those elements have been loaded into the DOM



来源:https://stackoverflow.com/questions/23438768/getelementbyid-returning-null

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