Reputation: 327
Can anyone tell me why I might be getting this error?
"TypeError: document.getElementById(...) is null @ line:25"
I am using JavaScript and this is what I have so far inside my <script>
tags...
var initBoard = new Array(new Array(0, 0, 0, 1),
new Array(0, 0, 0, 0),
new Array(3, 0, 0, 0),
new Array(0, 0, 2, 0)
);
function insertData(){
for(var i = 0; i < 4; i++){
for(var j = 0; j <4; j++){
document.getElementById(i.j).innerHTML = initBoard[i][j];
}
}
}
Below that inside my HTML <body>
I have this....
<table border="2" >
<tr align="center">
<td><div id="00">0</div></td>
<td><div id="01">0</div></td>
<td><div id="02">0</div></td>
<td><div id="03">0</div></td>
</tr>
<tr align="center">
<td><div id="10">0</div></td>
<td><div id="11">0</div></td>
<td><div id="12">0</div></td>
<td><div id="13">0</div></td>
</tr>
<tr align="center">
<td><div id="20">0</div></td>
<td><div id="21">0</div></td>
<td><div id="22">0</div></td>
<td><div id="23">0</div></td>
</tr>
<tr align="center">
<td><div id="30">0</div></td>
<td><div id="31">0</div></td>
<td><div id="32">0</div></td>
<td><div id="33">0</div></td>
</tr>
When I try and run this I get that error from above.
I have also tried to just hardcode the "ID" as '00'
or '01'
and it still gives me the same error message.
Does anyone know what I am doing wrong? I have looked all over the place and everywhere says basically the same thing and it should be easy, but I cannot get past this.
EDIT: Line 25 is document.getElementById(i.j).innerHTML = initBoard[i][j];
Upvotes: 0
Views: 3688
Reputation: 7698
Make sure the code executes after the document is fully loaded. Something like
window.addEventListener("load", function() {
<your current code>
},0);
As the other posters said, using something like "cell"+i+"_"+j is also a good idea. I'd put the underscore in so that "111" isn't ambiguous.
Upvotes: 2
Reputation: 2271
Yeah - same issue happened to me once. The problem is that:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
So you'll have to replace your way of assigning IDs
Also - your approach of i.j is not correct
Upvotes: 2
Reputation: 48789
You want to convert the numbers to strings and concatenate them.
document.getElementById(i + "" + j).innerHTML = ...
You had i.j
, which would take the number referenced by i
, and ask it for its j
property, which would return undefined
.
Upvotes: 3