Why is document.body null in my 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.
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 thewindow
object:window.addEventListener('load', function () { // ... // Place code here. // ... });
For the difference between between the
DOMContentLoaded
andload
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 thebody
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>