-1

I am trying to set a DOM element to a variable but when I console.log() the variable, it shows null.

var canvas = document.querySelector('canvas');
console.log(canvas); //null

but it is working perfect in the tutorial I'm following. Can anyone help me out?

DeSpider
  • 323
  • 2
  • 16

1 Answers1

0

Due to specification, querySelector() returns null if no matches are found. So you have no canvas nodes in the moment you are trying to get it. You should

  • make sure that your html document has canvas node
  • make sure that you run your script after the canvas node is set to the html document

The following html code will work for sure

    <canvas id="myCanvas"></canvas>
    <script>
        var canvas = document.querySelector('canvas');
        console.log(canvas);
    </script>
dhilt
  • 18,707
  • 8
  • 70
  • 85