Ben Pearce
Ben Pearce

Reputation: 7094

getElementById returning null for Canvas element

When I run the code below I get 'null' for the variable surface. Can anyone tell me what I'm doing wrong?

<html>

<body>
    <script>
        var surface = document.getElementById("myCanvas");
        console.log("surface: " + surface);
    </script>

    <canvas id="myCanvas" width="300" height="150">
        <p>Your browser doesn't support canvas.</p>
    </canvas>
</body>

</html>

Upvotes: 1

Views: 1162

Answers (2)

Josh
Josh

Reputation: 140

Place your javascript after the canvas, its quite possibly running before the canvas is rendered on the page.

Upvotes: 0

adeneo
adeneo

Reputation: 318182

The element doesn't exist yet when you're trying to get it, move the script tag so the element comes before it in the DOM

<html>

<body>
    <canvas id="myCanvas" width="300" height="150">
        <p>Your browser doesn't support canvas.</p>
    </canvas>

    <script>
        var surface = document.getElementById("myCanvas");
        console.log("surface: " + surface);
    </script>
</body>

</html>

Upvotes: 3

Related Questions