HelloWorld
HelloWorld

Reputation: 11247

Null while grabbing an element with .getElementById

I am trying to grab an element (a button) and add an event listener on it. Whenever I run

var button = document.getElementById('clickMe');
console.log(button); // null

I checked that my javascript file is loading and checked that everything is case sensitive. Here is my html and JS Files:

HTML:

<!doctype html>
<html>
  <head>
    <script src="js/timer.js"></script>
  </head>
  <body>
        <button id='clickMe' type='button'>Hello</button>
  </body>
</html>

JS

var button = document.getElementById('clickMe');
console.log(button);
function buttonClicked () {
  alert('the button was clicked');
}

button.addEventListener('click', buttonClicked);

function timerComplete () {
  alert('timer complete');
}

setTimeout(timerComplete, 2000);

The most common errors I have found was camel casing getelementbyid which I did.

Does anyone know why I keep getting null? Is it trying to grab the element before it is loaded?

Upvotes: 0

Views: 165

Answers (1)

Emilio Rodriguez
Emilio Rodriguez

Reputation: 5749

Your Javascript code is executed before the Button is added to the DOM. You could change your HTML to this:

<!doctype html>
<html>
  <body>
        <button id='clickMe' type='button'>Hello</button>
        <script src="js/timer.js"></script>
  </body>
</html>

Or even better, if you don't mind making your JS code a bit more complex you could wait for your dom elements to be loaded before executing that part of the code:

document.addEventListener('DOMContentLoaded', function() {
   var button = document.getElementById('clickMe');
   console.log(button);
});

If you use this JS you can put back your script tag back to the head

Upvotes: 2

Related Questions