This code is actually *NOT* the preferred way to add a row to a table:
Code:
function addTableRow() {
var newrow = document.createElement('tr');
// give your table an id..
var theTable = document.getElementById('table1');
theTable.appendChild(newrow);
...
The better way is this:
Code:
function addTableRow() {
var tbl = document.getElementById("theTable");
var newrow = tbl.insertRow(tbl.rows.length);
Complete working example:
Code:
<html>
<body>
<table id="theTable">
<tr><td>row 1</td></tr>
<tr><td>row 2</td></tr>
<tr><td>row 3</td></tr>
<tr><td>row 4</td></tr>
</table>
<input id="theButton" type="button" value="remove last row"/>
<input id="otherButton" type="button" value="clone last row"/>
<script type="text/javascript">
document.getElementById("theButton").onclick =
function() {
var tbl = document.getElementById("theTable");
var tbody = tbl.getElementsByTagName("tbody")[0];
var rows = tbody.getElementsByTagName("tr");
if ( rows.length > 0 )
{
tbody.removeChild( rows[rows.length-1] );
}
}
document.getElementById("otherButton").onclick =
function() {
var tbl = document.getElementById("theTable");
var newrow = tbl.insertRow(-1);
var newcell = newrow.insertCell(-1);
newcell.innerHTML = "row " + tbl.rows.length;
}
</script>
</body>
</html>