0

I'm trying to create spans and append split string as characters within each span. So, given the message below, it'd be something like <span>t</span><span>h</span> etc...

For some reason, I'm getting this error when I append to document body. Why?

Uncaught TypeError: Cannot read property 'appendChild' of null

<!doctype html>
<html>
  <head>

    <script type="text/javascript">

            scramble();

            function scramble () {                  
                var message = "this is a message";
                for (var i = 0; i < message.split("").length; i++) {
                    var letter = document.createElement('span');
                    letter.innerHTML = message.split("")[i];
                    document.body.appendChild(letter);
                    //document.getElementById("body").appendChild(letter);
                }
            }               
            function log (w) {
                console.log(w);
            }


    </script>
</head>
<body>      
</body>
</html>

I've also tried document.getElementById("body").appendChild(letter); with the same error.

Stack trace:

 Uncaught TypeError: Cannot read property 'appendChild' of null
 myFunc
 (anonymous function)
Growler
  • 10,676
  • 21
  • 100
  • 224

2 Answers2

4

Try to put your JavaScript at the bottom (anywhere below or inside the body tag).

Or use this if you don't have jQuery :

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

Or if you have jQuery :

$( document ).ready(function() {
    //do work
});

document.body still doesn't exist by the time scramble() is called.


References :

document.ready without jQuery

Community
  • 1
  • 1
Zaenille
  • 1,319
  • 8
  • 15
  • Yup. And by "at the bottom", you mean as the last child of the `body` element. However, since _this code_ in particular is only accessing `document.body`, it would work even as the first child of `body`. – Spooky Feb 26 '15 at 02:13
  • 1
    Thanks for bringing that up @Spooky, I edited in the definition of *bottom* in the answer to be more specific. – Zaenille Feb 26 '15 at 02:14
0

This is because you are calling the "scramble" method from within the HEAD tag before the BODY is actually rendered. Make the call to "scramble" run during the "unload" event or just call it from a SCRIPT tag places just before the closing BODY tags at the bottom of the page.

Chris Pietschmann
  • 28,196
  • 35
  • 116
  • 161