Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

103
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda