How to solve the Javascript-error „Cannot read property ‚appendChild‘ of null“!
07/17/2019 (5438x read)
If you want to append elements to the current document using Javascript, an error may occur. This happens if the script is executed before the document is completely loaded. If you want to append something to the DOM with the function appendChild(), the Chrome Browser will show this error message:
„Uncaught TypeError: Cannot read property ‚appendChild‘ of null“
or:
„Cannot call method ‚appendChild‘ of null“
The solution is to make sure that the Javascript code is only executed when the page has been completely loaded and the DOM has been completely created. Afterwards you can add or remove elements from the DOM via Javascript.
To make sure that the script is executed after loading the page, you can place it at the bottom of the page. But it is safer to put the code into a function that is executed only after the page has loaded: This works in Javascript with „window.onload“.
The code to add something to the DOM via appendChild() might look like this:
window.onload = newdiv(); function newdiv(){ var div=document.createElement('div'); div.id='new div'; document.body.appendChild(div); }
The error „Uncaught TypeError: Cannot read property ‚appendChild‘ of null“ or „Cannot call method ‚appendChild‘ of null“ is now avoided by the new function which is loaded at „window.onload“!