Note: this is meant to be a community wiki post
The following code using simple dom methods fails to add rows to the table. What’s the issue?
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytable = document.getElementById('mytable');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytable.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tr>
<td>This is a row</td>
</tr>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
The issue at hand here is that the
<table>element’s correct structure is not present. When dealing with tables, the basic structure is:The logic is that when dealing with tables, you want to keep the labels of the columns, and the actual data separate. Because most browsers fill in the
<tbody>as part of the process of fixing broken HTML, few people realize this. When the browser sees you adding a<tr>, it doesn’t know if you’re trying to add it to the<thead>or the<tbody>, so it fails.The following shows the correct method for adding the rows: