Search code examples
javascriptappendchild

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?


Solution

  • 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);
    }