"Referenceerror: Document is not defined" in querySelector

Asked

Viewed 3,740 times

0

I’m running some tests here and I’m making a mistake:

The index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>teste</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="scripts/teste.js" defer></script>


</head>

<body onload="inicializar();">

    <img src="imagens\mold_tv.png" width="1345px" height="660px">

    <canvas id="canvas" width="760" height="500" onclick="clickOnUI()">
    </canvas>

    <form name="form">
        <input type="text" name="cronometro" id="cron" value="00:00:00" />

    </form>

</body>
</html>

The test.js:

(function(){
    let canvas = document.querySelector("#canvas");//pega o componente canvas

     let jogador = {
        altura: 100,
        largura: 40,
        velocidadeX: 40,
        velocidadeY: 10,
        posX: (canvas.width-100) /2,
        posY(){return(canvas.height-20)+this.velocidadeY}

     }

     console.log(jogador.largura)


})();

And when running test.js on Node gives the following error:

let canvas = document.querySelector("#canvas")//pega o componente canvas
             ^

ReferenceError: document is not defined
    at /home/note/Área de Trabalho/jog_tcc/jogo_tcc/scripts/teste.js:2:18
    at Object.<anonymous> (/home/note/Área de Trabalho/jog_tcc/jogo_tcc/scripts/teste.js:18:3)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3
  • 1

    This may help you: https://stackoverflow.com/q/32126003/1377664

  • 4

    Your code does not work in the browser because it tries to find the canvas before it exists in the document. See the browser console, there will be errors there. In the Node it fails because document is a DOM object, exists only in the browser.

1 answer

0


Document is a DOM object that only exists in the browser. In order to run this script you will have to install the Browserify.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.