Rectangle 27 0

google chrome Why is document.body null in my javascript?


<!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>
DOMContentLoaded
document.addEventListener('DOMContentLoaded', function () {
    // ...
    // Place code here.
    // ...
});
load
window.addEventListener('load', function () {
    // ...
    // Place code here.
    // ...
});

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

I think this is more thorough and current than the accepted answer.

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

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.

There are a couple ways to workaround this.

Wrap your logic in an event listener for DOMContentLoaded.

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

Note
Rectangle 27 0

google chrome Why is document.body null in my 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 ;)

Note
Rectangle 27 0

google chrome Why is document.body null in my javascript?


<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>

@TomBrito: "or place it after the <body> tag"

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.

The page is read from top to bottom and javascript executed along the way. You have some javascript in the head section that is being executed. But body part of the html, maybe, hasn't been even downloaded yet. Or it is downloaded, but it's still not evaluated at this point. So it doesn't exist in the DOM.

What if you don't want to override an existing onload defined in another file?

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).

Note