I am just doing a Javascript excercise which should add a row into a table. Html reads like this:
<!DOCTYPE html>
<html><head><br><meta charset=utf-8 />
</head><body>
<table id="sampleTable" border="1">
<tr><td>Row1 cell1</td>
<td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td>
<td>Row2 cell2</td></tr>
</table><br>
<input type="button" onclick="insert_Row()" value="Insert row">
</body></html>
And my script that doesn't work:
function insert_Row(){
var xTable=document.getElementById('sampleTable');
for (i=0;i<=xTable.children.length;i++)
{
if(i===xTable.children.length)
{
xTable.createElement('tr');
tr.innerHTML ='<td>cell1</td><td>cell2</td>'
}
}
}
This is the correct solution:
function insert_Row()
{
var x=document.getElementById('sampleTable').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML="New Cell1";
z.innerHTML="New Cell2";
}
I would like to understand what is wrong with my first solution? Why doesn't it create the tag but throws error instead?