`getElementById` returning null [duplicate]

2019-03-04 12:26发布

问题:

This question already has an answer here:

  • Why does jQuery or a DOM method such as getElementById not find the element? 6 answers

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