tprieboj
tprieboj

Reputation: 1703

Cant use DOM in js

I want to make dynamical table using DOM. This code is not working. I am receiving this error

Uncaught TypeError: Cannot read property 'insertRow' of null

js

 var persons = [
       { name:"Jurij Gagarin", birth: "9 March 1934", death:"27 March 1968" },
       { name:"Albert Einstein", birth: "14 March 1879", death:"18 April 1955 " },
       { name:"Mahatma Gandhi", birth: "2 October 1869", death:"30 January 1948" },
       { name:"Whitney Houston", birth: "9 August 1963", death:"11  February 2012" },];    
    function init() {
        table = document.getElementById('personsTab');
        tableSize = persons.length;
        //personsTab
        for(var i = 0; i < tableSize; i++){
            var row = table.insertRow(i);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            cell1.innerHTML = persons[i].name;
            cell2.innerHTML = persons[i].birth;
            cell3.innerHTML = persons[i].death;
        }
    } 
    window.onload = init();

html

    <table id="personsTab"> 
    <tr>
        <th id="name"><span>Name<span></th>
        <th id="birth"><span>Birth<span></th>
        <th id="death"><span>Death<span></th>
    </tr>
</table>

Upvotes: 1

Views: 217

Answers (3)

tabz100
tabz100

Reputation: 1473

You should probably change window.onload = init(); to window.onload = init (without the parentheses) because you do not actually want to call the function. You just want to assign the reference to the function to the window.onload event

Upvotes: 2

FabioCosta
FabioCosta

Reputation: 2769

You are calling the function before the load you have to make

    window.onload = function(){init();}

Or to be more cleaner

    window.onload = init;

The problem was you calling the function and not passing it

Upvotes: 2

pingbattlespl0x
pingbattlespl0x

Reputation: 67

I think you are having a scope problem. Because you did not declare table as a var, it is not visible inside the for loop.

Try

var table = document.getElementById('personsTab');

Upvotes: 0

Related Questions