Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i'm getting an Uncaught TypeError: Cannot set property 'onclick' of null? [duplicate]

Tags:

javascript

dom

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);
};
like image 307
varun teja Avatar asked Mar 14 '23 03:03

varun teja


1 Answers

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>
like image 190
j08691 Avatar answered Apr 25 '23 09:04

j08691