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);
};
3
  • for one thing, you dice isn't defined anywhere. The button seems fine. Commented Nov 19, 2015 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 Commented Nov 19, 2015 at 16:01
  • A better duplicate is probably Why does jQuery or a DOM method such as getElementById not find the element? Commented Nov 19, 2015 at 16:04

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.