Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
Why does my JavaScript variable return 'null' instead of Html?

I have some JavaScript that is not working:


    const player = document.getElementById("player");
    console.log(player);
    
    var positionX = 600;
    var positionY = 200;
    
    document.onkeypress = function move(e) {
      console.log(e.key);
      let keyPressed = e.key;
      if (keyPressed == 'w') {
        positionY--;
        player.style.top = positionY + 'px';
        console.log(player);
      }
    };

And in the console, the 'player' variable prints as 'null' when I have tried setting it to the 'player' div in my Html.

Here is the Html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Movement</title>
    <link rel="stylesheet" href="index.css">
    <script src="index.js" charset="utf-8"></script>
  </head>
  <body>

    <div id="player"></div>

  </body>
</html>

An error also shows up:

index.js:12 Uncaught TypeError: Cannot read properties of null (reading 'style')
    at HTMLDocument.move (index.js:12:12)
move @ index.js:12

Can someone help me?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is because your JavaScript searches for the element before the DOM is rendered, so the player variable is instead null.

You can add the script after the player div:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Movement</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>

    <div id="player"></div>
    <script src="index.js" charset="utf-8"></script>
  </body>
</html>

or wait for the DOM to be rendered with

document.addEventListener("DOMContentLoaded", () => {
  const player = document.getElementById("player");
    console.log(player);
    
    var positionX = 600;
    var positionY = 200;
    
    document.onkeypress = function move(e) {
      console.log(e.key);
      let keyPressed = e.key;
      if (keyPressed == 'w') {
        positionY--;
        player.style.top = positionY + 'px';
        console.log(player);
      }
    };
});
about 4 years ago · Juan Pablo Isaza Relatório

0

You should put you script inside window.onload()

Example :

window.onload = () => {
    /* put you script here */
}

Or call you js file at bottom of HTML

Because you script executed before all html element ready !

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda