4

i'm getting uncaught type error of: Uncaught TypeError: Cannot set property 'onclick' of null

<!DOCTYPE html>
<html>
    <head>
        <title>dice app</title>
        <script src="widget.js"></script>
    </head>
    <body>
        <button id="button">Roll Dice</button>
    </body>
</html>

js code:

var button = document.getElementById("button");

button.onclick = function() {// error
    var print = dice.roll();
    printNumber(print);
};
varun teja
  • 244
  • 3
  • 10
  • for one thing, you `dice` isn't defined anywhere. The button seems fine. – nem035 Nov 19 '15 at 16:00
  • 1
    you probably need to put this code in an "onload" function, because if you put it plain in the window root, it is probably going to be executed before the page is completely loaded and then the button object doesn't exist – RiccardoC Nov 19 '15 at 16:01
  • A better duplicate is probably [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/q/14028959/218196) – Felix Kling Nov 19 '15 at 16:04

2 Answers2

5

You're executing your JavaScript before the elements exist. Either move your code to the end of the page or put it within an onload handler.

Ex:

<!DOCTYPE html>
<html>
    <head>
        <title>dice app</title>
    </head>
    <body>
        <button id="button">Roll Dice</button>
        <script src="widget.js"></script>
    </body>
</html>
j08691
  • 190,436
  • 28
  • 232
  • 252
2

Move your script after the button in the HTML. Currently the script is being evaluated but the HTML element hasn't been created yet.

Danny H
  • 336
  • 2
  • 7