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>
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
headsection that usesbody. Not cool.You want to wrap this code in a
window.onloadhandler or place it after the<body>tag (as mentioned by e-bacho 2.0).See demo.