0

I just started coding with JavaScript and i decided to run some code. (shown below)

var handleClick = function (event) {
    alert('Hello there!');
};
var button = document.querySelector('#big-button');
button.addEventListener('click', handleClick);

However, whenever I would run the code it would say the button is null. help?

Youngjin Song
  • 11
  • 1
  • 1
  • 2
    if the `document.querySelector()` method cannot find a DOM element with an id of `big-button`, it will return `null` – jonny Aug 26 '15 at 16:05
  • 3
    Is there any element with id `big-button` in your DOM? – sp00m Aug 26 '15 at 16:05
  • If you have a DOM element with `id="big-button"`, then you are probably just running this code too soon before the page has been parsed by the browser. Put this code in a ` – jfriend00 Aug 26 '15 at 16:09

4 Answers4

7

From the documentation:

Returns null if no matches are found; otherwise, it returns the first matching element.

So, at the time you run querySelector there is no element in the DOM which has the ID big-button.

This is usually caused by putting the script in the head and trying to access elements in the body. Approaches to deal with this include:

  • Moving the <script> so it appears after the element you are trying to access. This could be directly after it or just before the </body> tag.
  • Wrap the code in a function and bind that function as a load event handler.
  • Bind the event listener to the window and test event.target when the event fires to see if it matches the element.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

In this instance, it means that the variable 'button' is null when you try and execute the line button.addEventListener('click', handleClick). This would happen if you don't have an element on the page when that code executes that has an id of 'big-button' which you're trying to retrieve with the call to document.querySelector('#big-button');

Chris Disley
  • 1,286
  • 17
  • 30
0

Move your code inside the onload block

window.onload = function(){
    var button = document.querySelector('#big-button');
    button.addEventListener('click', handleClick);

}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0
<button id="big-button">click me</button>
    <script>

        var handleClick = function (event) {
            alert('Hello there!');
        };
        var button = document.querySelector('#big-button');
        button.addEventListener('click', handleClick);
    </script>
START
  • 11
  • 1
  • A block of code with no explanation is pretty much never as good an answer as it could be with some explanation added. – jfriend00 Aug 26 '15 at 16:28