Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!