Javascript: AppendChild

Ryan picture Ryan · Jul 29, 2011 · Viewed 62.7k times · Source

I was learning about appendChild and have so far come up with this code:

But that gives me an error saying Uncaught TypeError: Cannot call method 'appendChild' of null. What am I doing wrong?

Answer

George P picture George P · Jul 29, 2011

Try wrapping your JavaScript in an onload function. So first add:

<body onload="load()">

Then put your javascript in the load function, so:

function load() {
    var blah="Blah!";
    var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    tr = document.createElement("tr"),
    td = document.createElement("td");

    t.style.width = "100%";
    t.style.borderCollapse = 'collapse';

    td.appendChild(document.createTextNode(blah)); 

    // note the reverse order of adding child        
    tr.appendChild(td);
    tb.appendChild(tr);
    t.appendChild(tb);

   document.getElementById("theBlah").appendChild(t);
}