Why is document.body null in my javascript?

JavascriptGoogle Chrome

Javascript Problem Overview


Here is my brief HTML document.

Why is Chrome Console noting this error:

>"Uncaught TypeError: Cannot call method 'appendChild' of null"?

<html>
<head>
    <title>Javascript Tests</title>
    
    <script type="text/javascript">
        
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";
        
        mySpan.style.color = "red";
        document.body.appendChild(mySpan);
        
        alert("Why does the span change after this alert? Not before?");
        
    </script>
</head>
<body>

</body>
</html>

Javascript Solutions


Solution 1 - Javascript

The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head section that uses body. Not cool.

You want to wrap this code in a window.onload handler or place it after the <body> tag (as mentioned by e-bacho 2.0).

<head>
    <title>Javascript Tests</title>

    <script type="text/javascript">
      window.onload = function() {
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");
      }

    </script>
</head>

See demo.

Solution 2 - Javascript

Your script is being executed before the body element has even loaded.

There are a couple ways to workaround this.

  • ###Wrap your code in a DOM Load callback:

    Wrap your logic in an event listener for DOMContentLoaded.

    In doing so, the callback will be executed when the body element has loaded.

      document.addEventListener('DOMContentLoaded', function () {
          // ...
          // Place code here.
          // ...
      });
    

    Depending on your needs, you can alternatively attach a load event listener to the window object:

      window.addEventListener('load', function () {
          // ...
          // Place code here.
          // ...
      });
    

    For the difference between between the DOMContentLoaded and load events, see this question.

  • Move the position of your <script> element, and load JavaScript last:

    Right now, your <script> element is being loaded in the <head> element of your document. This means that it will be executed before the body has loaded. Google developers recommends moving the <script> tags to the end of your page so that all the HTML content is rendered before the JavaScript is processed.

      <!DOCTYPE html>
      <html>
      <head></head>
      <body>
        <p>Some paragraph</p>
        <!-- End of HTML content in the body tag -->
    
        <script>
          <!-- Place your script tags here. -->
        </script>
      </body>
      </html>
    

Solution 3 - Javascript

Add your code to the onload event. The accepted answer shows this correctly, however that answer as well as all the others at the time of writing also suggest putting the script tag after the closing body tag, .

This is not valid html. However it will cause your code to work, because browsers are too kind ;)

See this answer for more info https://stackoverflow.com/questions/3037725/is-it-wrong-to-place-the-script-tag-after-the-body-tag

Downvoted other answers for this reason.

Solution 4 - Javascript

Or add this part

<script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>

after the HTML, like:

    <html>
    <head>...</head>
    <body>...</body>
   <script type="text/javascript">
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");

    </script>

    </html>

Solution 5 - Javascript

Browser parses your html from top down, your script runs before body is loaded. To fix put script after body.

  <html>
  <head>
       <title> Javascript Tests </title> 
  </head>
 <body>
 </body>
  <script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>
</html>

Solution 6 - Javascript

document.body is not yet available when your code runs.

What you can do instead:

var docBody=document.getElementsByTagName("body")[0];
docBody.appendChild(mySpan);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn HoffmanView Question on Stackoverflow
Solution 1 - JavascriptSergio TulentsevView Answer on Stackoverflow
Solution 2 - JavascriptJosh CrozierView Answer on Stackoverflow
Solution 3 - JavascriptMartin HansenView Answer on Stackoverflow
Solution 4 - JavascriptBoris BachovskiView Answer on Stackoverflow
Solution 5 - JavascriptEmmanuel NView Answer on Stackoverflow
Solution 6 - JavascriptChristopheView Answer on Stackoverflow