0

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?

2
  • 3
    Your script executes before the DOM is loaded, so the element is not there at the first place to be targeted by your script. Load the script at the end of the document or use document.onload to have the DOM loaded when the script executes. Commented Feb 21, 2014 at 21:12
  • 1
    Yes, it is trying to get the element before it loads. Take a look at window.onload Commented Feb 21, 2014 at 21:12

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

This, even if it works, looks quite wrong to me. The code from the question is looking forward to get a $( document ).ready() ...
it's a quick fix. Of course the best approach is wait for the dom to be ready. But if there is no JQuery involved it complicates the implementation for a novice developer
Thanks guys, yeah I was just trying to get some practice with callbacks. A silly mistake of me to not see this earlier. Thanks for the fix @emilioicai
You are 100% correct, but at the same time maybe it is better to get him on the right way from the beginning, anyways problem solved !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.