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

99
Visualizações
Cannot set property innerText

html:

<!DOCTYPE html>
<html>
    <head>
<script src="plm.js"></script>
    </head>
    <body>
<h1 id="element">number</h1>
<button onclick="bruh()">Add Num</button>

    </body>



</html>

js

let nr = 0
let change = document.getElementById("element")
function bruh(){
    nr = nr + 1
 change.innerText = nr
}

I get this error "plm.js:5 Uncaught TypeError: Cannot set properties of null (setting 'innerText')

I know that if I write for example document.getElementById(element).innerText = nr it will work but when I have used replit to write code it worked with putting it in a variable but on vscode is not the same

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

0

It is likely that this line:

   let change = document.getElementById("element")

... is being called before the #element h1 is in the DOM.

A quick fix would be to move this line inside the click callback as I have shown below.

A probably better fix would be defer the execution of your script until a time when you know the element is in the dom, for example: DOMContentLoaded event

Other options as the commenters have pointed out include using the defer attribute or moving the <script> tag to just before the closing </body> tag.

let nr = 0
function bruh(){
   let change = document.getElementById("element")
    nr = nr + 1
 change.innerText = nr
}
<h1 id="element">number</h1>
<button onclick="bruh()">Add Num</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Your javascript file is running before it can access the DOM.

Change this:

<script src="plm.js"></script>

to this:

<script src="plm.js" defer></script>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer

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