Reputation: 1703
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
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
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
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