Ben Ben - 1 year ago 131
Javascript Question

Javascript error - cannot call method 'appendChild' of null

I am new to Javascript (and programming in general) and have been trying to get a basic grasp on working with the DOM. Apologies if this is a very basic mistake, but I looked around and couldn't find an answer.

I am trying to use the appendChild method to add a heading and some paragraph text into the in the very basic HTML file below.

<title>JS Practice</title>
<script src="script.js"></script>
<div id = "main">
<h1>Simple HTML Page</h1>
<p>This is a very simple HTML page.</p>
<p>It's about as basic as they come. It has: </p>
<li>An H1 Tag</li>
<li>Two paragraphs</li>
<li>An unordered list</li>
<div id="javascript">

Here is the js code:

var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");

newHeading.innerHTML = "New Heading!";
newParagraph.innerHTML = "Some text for a paragraph.";


Running it causes an error: "Cannot call method 'appendChild' of null"

Help? I can't figure out why this isn't working...

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download