Javascript: Typeerror: Document.getelementbyid("mytable") Is Null
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 neve
Solution 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.
Solution 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><scripttype="text/javascript">functioncolorRows(){
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><tableid="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><formmethod="post"action="JavaScript:colorRows();"><inputtype="submit"value="Submit" /></form></body></html>
Solution 3:
Try this
functioncolorRows(){
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()
Post a Comment for "Javascript: Typeerror: Document.getelementbyid("mytable") Is Null"