Javascript: AppendChild
Asked Answered
A

6

7

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?

Abdullah answered 28/7, 2011 at 23:29 Comment(1)
You can also place your script below theBlah and it will work without an onload listener.Deltoid
S
23

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);
}
Seating answered 28/7, 2011 at 23:34 Comment(0)
Y
11

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

<script>
window.onload = function () {
    var blah="Blah!";
    var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    ...
    //the rest of your code here
};
</script>
Yemane answered 28/7, 2011 at 23:41 Comment(0)
B
7

The problem is that document.getElementById("theBlah") returns null. The reason why is that your code is running before the theBlah element has been created. You should place your code in an onload event handler.

Boast answered 28/7, 2011 at 23:35 Comment(0)
K
2

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:

  1. use native JavaScript (not slowing down JQuery)

  2. (function(){})() executes the code before body is loading

  3. doesn’t have problems with other variables outside the function

  4. and pass the document so you have shorter variables

  5. there is a way to shorten the function by using clone node... but it’s slower and maybe not supported by all browsers

  6. use createDocumentFragment() to create the tr’s. If you have a lot of rows this helps to build the DOM faster.

    (function (d) {
        var rows = 10,
            cols = 3,
            t = d.createElement('table'),
            the = d.createElement('thead'),
            tb = d.createElement('tbody'),
            tr = d.createElement('tr');
        t.style.width = "100%";
        t.style.borderCollapse = 'collapse';
        for (var a = 0; a < cols; a++) {
            var th = d.createElement('th');
            th.innerText = Math.round(Math.random() * 100);
            tr.appendChild(th);
        };
        the.appendChild(tr);
        var f = d.createDocumentFragment();
        for (var a = 0; a < rows; a++) {
            var tr = d.createElement('tr');
            for (var b = 0; b < cols; b++) {
                var td = d.createElement('td');
                td.innerText = Math.round(Math.random() * 100);
                tr.appendChild(td);
            }
            f.appendChild(tr);
        }
        tb.appendChild(f);
        t.appendChild(the);
        t.appendChild(tb);
        window.onload = function () {
            d.body.appendChild(t)
        };
    })(document)
Keen answered 4/6, 2013 at 1:8 Comment(0)
D
1

I believe you can just link your JavaScript to your html using the defer attribute.

<script src="script.js" defer></script>

This way your JavaScript will not run until after the page has loaded.

Dotty answered 7/10, 2020 at 23:54 Comment(0)
T
-2

Do yourself and us a favor and use JQuery. Everything becomes much simpler.

$('div.SomeDiv').append($('<table></table>').css('width','100%').append($('<tbody></tbody>').append($('<tr></tr>').append($('<td></td>').html("Blah Text"))))); // Everything else you want to add here...
Tonyatonye answered 28/7, 2011 at 23:37 Comment(6)
I am only using JS to make some changes to a Firefox plugin... i am not sure what their policies are on JQuery...Abdullah
JQuery is translated finally into Javascript you know... I'm hard to believe there is a different...Tonyatonye
@Abdullah - if you want to learn javascript, don't start with jQuery. If you learn javascript first, you will be able to use libraries and frameworks much more effectively and efficiently later.Deltoid
@Tonyatonye jQuery doesn't get translated, it's native JavaScript (during development it's built with Ant, but that doesn't matter). You can open jQuery source file and change anything you want, in JavaScript.Prussia
jQuery is a fantastic library, but this answer has little place here. The example you have given is sloppy and using jQuery in every instance as you've suggested is often over kill. @Ryan's advice is very wiseTutty
This is the completely wrong advice. I learned the hard way to not learn jQuery first. It doesn't teach you the crucial foundations you need to know.Trail

© 2022 - 2024 — McMap. All rights reserved.