Commonly you see the Uncaught TypeError: cannot set property innerText of null error if you try to access an HTML element on a page before it appears.
An Example Situation
Let’s say you are asking for user input to display a greeting on a front page.
If you open the index.html file, the page shows a prompt that asks a user for their name:
If you now open up the console, you can see there is an error:
Uncaught TypeError: Cannot set properties of null (setting 'innerText')
This error says the code tries to set the property innerText of null, which is obviously not possible as there is no such property on a null object.
But why does the document.getElementById(“welcome”) return null, and not a HTML element in the first place? There is an HTML element with that ID, right?
This happens because the script tries to access that HTML element before it appears on the page.
But why is that?
To run the script after the element has appeared on the page, you need to place the script after that element in the HTML.
In this case, let’s move the script below the h1 tag:
If you now open up the index.html with your browser, you can see that the greeting works!
Thanks for reading.