Home > Blockchain >  Cannot set property innerText
Cannot set property innerText

Time:08-24

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 erro "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 puting it in a variable but on vscode is not the same

CodePudding user response:

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>

CodePudding user response:

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

  • Related