Pergunta

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?

Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top