javascripthtmlinnertext

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


Solution

  • 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>