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?

1 Response to “JavaScript appendChild returning null”


  1. 1 Michael

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

Leave a Reply