Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: AppendChild

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

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);
<div id="theBlah">d</div>

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

like image 952
Ryan Avatar asked Jul 28 '11 23:07

Ryan


1 Answers

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);
}
like image 105
George P Avatar answered Sep 18 '22 07:09

George P