简体   繁体   中英

Why is document.getElementById returning a null value?

I've debugged my code and realized that a method in my Javascript isn't working properly. Anyone have an idea why?

index.html :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tetris</title>
<link rel="stylesheet" href="css/app.css">
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<canvas id="tetrisBoard" width="800" height="600">
  Your browser does not support HTML 5.
</canvas>
<p>
</p>
</body>
</html>   

main.js :

board = document.getElementById("tetrisBoard")                                                                                                                                                              
ctx = board.getContext("2d")
ctx.fillStyle = "rgb(200, 0, 0)"
ctx.fillRect 10, 10, 55, 50

The result of document.getElementById("tetrisBoard") is a null value. Why?

Because you're calling your code prior to the elements existing. Put the script right before the closing body tag and you'll be fine.

Another solution is to do something like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Tetris</title>
        <link rel="stylesheet" href="css/app.css">
        <script type="text/javascript" src="js/main.js"></script>
    </head>
    <body onload="setup();">
        <canvas id="tetrisBoard" width="800" height="600">
            Your browser does not support HTML 5.
        </canvas>
        <p>
        </p>
   </body>
</html>

Then, in your main.js use something like this:

function setup() {
    // Your code here
}

The good thing about this is that you don't have to put the script tag in an unintuitive and unstandard spot (such as right before the end of the body).

Also you could make the script to wait until all the DOM it is loaded... like this:

using jquery

 $(document).ready(function(){
    board = document.getElementById("tetrisBoard")                                                                                                                                                              
ctx = board.getContext("2d")
ctx.fillStyle = "rgb(200, 0, 0)"
ctx.fillRect 10, 10, 55, 50
    });

vanilla JavaScript:

    document.addEventListener("DOMContentLoaded", function () {
      board = document.getElementById("tetrisBoard")                                                                                                                                                              
ctx = board.getContext("2d")
ctx.fillStyle = "rgb(200, 0, 0)"
ctx.fillRect 10, 10, 55, 50
      }, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM