title: Uncaught TypeError: Cannot read property 'appendChild' of null
body: <p>I'm getting the following error</p>
  
  <blockquote>
    <p>Uncaught TypeError: Cannot read property 'appendChild' of null</p>
    
    <p>myRequest.onreadystatechange @ script.js:20</p>
  </blockquote>
  
  <p>with my following code</p>
  
  <pre><code>// index.html 
  &lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;Simple Page&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;div id="mainContent"&gt;
              &lt;h1&gt;This is an AJAX Example&lt;/h1&gt;
          &lt;/div&gt;
          &lt;script type="text/javascript" src="script.js"&gt;&lt;/script&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>And here is my JavaScript file</p>
  
  <pre><code>// script.js
  // 1. Create the request
  
  var myRequest;
  
  // feature check!
  if(window.XMLHttpRequest) { // Firefox, Safari
      myRequest = new XMLHttpRequest();
  } else if (window.ActiveXObject){ // IE
      myRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  
  // 2. Create an event handler for our request to call back 
  myRequest.onreadystatechange = function() {
      console.log("We were called!");
      console.log(myRequest.readyState);
      if(myRequest.readyState === 4){
          var p = document.createElement("p");
          var t = document.createTextNode(myRequest.responseText);
          p.appendChild(t);
          document.getElementById("mainContent").appendChild(p);
      }
  };
  
  // 3. open and send it
  myRequest.open("GET","simple.txt", true);
  
  // any parameters?
  myRequest.send(null);
  </code></pre>
  
  <p>And here is the contents of <code>simple.txt</code></p>
  
  <blockquote>
    <p>This is the contents of a simple text file.</p>
  </blockquote>
  
  <p>I put the script tag at the bottom of the html <a href="https://stackoverflow.com/questions/8670530/javascript-error-cannot-call-method-appendchild-of-null">as suggested by @Tejs here</a> but I'm still getting this error. </p>