问题
i'm getting the following error:
TypeError: document.getElementById("myTable") is null
on document.write(document.getElementById("myTable").rows[i].innerHTML); It goes into a never ending loop.
Can someone tell me on what i'm doing wrong? Thank you.
My code:
<script type="text/javascript">
function colorRows(){
count=document.getElementById("myTable").rows.length;
alert("count is:"+count);
for (i=0;i<=count;i++){
if (i%2===0){
document.write(document.getElementById("myTable").rows[i].innerHTML);
}
}
}
</script>
</head>
<body>
<table id="myTable">
<tr>
<th>emp_id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>vaani</td>
<td>35</td>
</tr>
<tr>
<td>2</td>
<td>Ramu</td>
<td>37</td>
</tr>
<tr>
<td>3</td>
<td>Iniyan</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>Mickey</td>
<td>10</td>
</tr>
</table>
<form method="post" action="JavaScript:colorRows();">
<input type="submit" value="Submit" />
</form>
</body>
</html>
回答1:
It is because when you do document.write
in the loop in the first time you clear dom and there is no more table element, and when you do document.write
in the second time then document.getElementById("myTable")
provides null
. So browser stops the script provide the error.
回答2:
I have the same error when I run your code. I put myTable to a new variable outside of for. It works fine. like that.
var myTableVar = document.getElementById("myTable");
var i;
for (i=0;i<=count;i++){
alert("i = " + i);
if (i%2===0){
document.write(myTableVar.rows[i].innerHTML);
}
}
Complete code:
<html>
<head>
<script type="text/javascript">
function colorRows(){
count=document.getElementById("myTable").rows.length;
alert("count is:" + count);
var myTableVar = document.getElementById("myTable");
var i;
for (i=0;i<=count;i++){
alert("i = " + i);
if (i%2===0){
document.write(myTableVar.rows[i].innerHTML);
}
}
}
</script>
</head>
<body>
<table id="myTable">
<tr>
<th>emp_id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>vaani</td>
<td>35</td>
</tr>
<tr>
<td>2</td>
<td>Ramu</td>
<td>37</td>
</tr>
<tr>
<td>3</td>
<td>Iniyan</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>Mickey</td>
<td>10</td>
</tr>
</table>
<form method="post" action="JavaScript:colorRows();">
<input type="submit" value="Submit" />
</form>
</body>
</html>
回答3:
Try this
function colorRows(){
var table = document.getElementById("myTable");
count=table.rows.length;
alert("count is:"+count);
for (i=0;i<=count;i++){
if (i%2===0){
document.write(table.rows[i].innerHTML);
}
}
}
Best to only access the table once anyway. document.write() clears the page because it calls document.open()
来源:https://stackoverflow.com/questions/12471249/javascript-typeerror-document-getelementbyidmytable-is-null