Hello!

I'm trying to add a div element to the DOM, and in return I get an error:

Uncaught TypeError: Cannot call method 'appendChild' of null

HTML code:

<html> <head> </head> <body> <script src="source.js"></script> <div id="something"> </div> </body> </html> 

Javascript code (source.js file):

 var div = document.createElement("div"); div.innerHTML = "Something new..."; document.getElementById("something").appendChild(div); 

What is the reason?

  • 3
    wrap the code in onload , because at the time of executing the code <div id="something"> not yet been created and therefore .getElementById("something") returns null - Specter

1 answer 1

@Spectre gave the correct explanation: at the time of executing the code, the <div id="something" /> element has not yet been created. Therefore, you need to transfer the execution of the code to the moment when the div is already created. For example:

 <body> <div id="something"> </div> <script src="source.js"></script> </body>