Javascript error – cannot call method ‘appendChild’ of null

Assuming this code is inside the script.js file, this is because the javascript is running before the rest of the HTML page has loaded.

When an HTML page loads, when it comes across a linked resource such as a javascript file, it loads that resource, executes all code it can, and then continues running the page. So your code is running before the <div> is loaded on the page.

Move your <script> tag to the bottom of the page and you should no longer have the error. Alternatively, introduce an event such as <body onload="doSomething();"> and then make a doSomething() method in your javascript file which will run those statements.

Leave a Comment