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>
It is because when you do
document.writein the loop in the first time you clear dom and there is no more table element, and when you dodocument.writein the second time thendocument.getElementById("myTable")providesnull. So browser stops the script provide the error.