JavaScript appendChild returning null

Update: Thanks to Michael in the comments for the solution. I forgot that JS begins executing before the DOM is finished loading.

I’m trying to get the following code to work, but it’s failing:

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

        var ul = document.getElementById("list");

        var li = document.createElement("li");
        var litext = document.createTextNode("test");
        li.appendChild(litext);
        ul.appendChild(li);

        </script>
    </head>
    <body>
        <h1></h1>
        <ul id="list">
        </ul>
    </body>
</html>

Any thoughts?

This entry was posted in General. Bookmark the permalink.

2 Responses to JavaScript appendChild returning null

  1. Michael says:

    That code executes when it’s loaded; since when that code executes, the ul is not created yet. (you get the same problem if you move the script to the body before the ul is created). I would encapsulate that into a function that is executed on an event (eg, body onload=”init_page()” or whatever).

    If you’re not already, I suggest using Firebug for Firefox- it makes javascript debugging infinitely easier. Looking into a javascript framework, such as MochiKit, will also make life a lot better (at least, it did for me).

  2. Nino Paolo says:

    Yeah! *Micheal is correct. try it this way. Javascript DOM: appendChild

        window.onload = function(){
            var ul = document.getElementById("list");
            var li = document.createElement("li");
            var litext = document.createTextNode("test");
            li.appendChild(litext);
            ul.appendChild(li);
        };
        </script>
    </head>
    <body>
        <h1>AppendChild</h1>
        <ul id="list">
        </ul>
    </body>
    

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>