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?
Try wrapping your JavaScript in an onload function. So first add:
Then put your javascript in the load function, so:
Do yourself and us a favor and use JQuery. Everything becomes much simpler.
The script is being run before the page completes loading. Which is why document.getElementById("theBlah") returns null.
Either use something like jQuery or simply something like
proper way (rows & cols & the random innerText is set dynamically ...by you) this way is probably not the shortest but by way the fastest to build a table. It’s also a full table with
thead
and filled with random text:use native JavaScript (not slowing down JQuery)
(function(){})()
executes the code before body is loadingdoesn’t have problems with other variables outside the function
and pass the document so you have shorter variables
there is a way to shorten the function by using clone node... but it’s slower and maybe not supported by all browsers
use
createDocumentFragment()
to create thetr
’s. If you have a lot of rows this helps to build the DOM faster.The problem is that
document.getElementById("theBlah")
returns null. The reason why is that your code is running before thetheBlah
element has been created. You should place your code in anonload
event handler.