onteria_ onteria_ - 3 months ago 7
HTML Question

I'm trying to add some rows to an HTML table, but it's failing

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>

Answer

The issue at hand here is that the <table> element's correct structure is not present. When dealing with tables, the basic structure is:

<table>
<thead>
<tr>
  <th>Heading for the table</th>
</tr>
</thead>
<tbody>
  <tr>
    <td>A row of data</td>
  </tr>
</tbody>
</table>

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:

<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
    var mytbody = document.getElementById('mytbody');

    var row = document.createElement('tr');
    var cell = document.createElement('td');
    var text = document.createTextNode('This is a row');

    cell.appendChild(text);
    row.appendChild(cell);
    mytbody.appendChild(row);
}
</script>
</head>
<body>
<form action="#">

<table id="mytable">
<tbody id="mytbody">
<tr>
    <td>This is a row</td>
</tr>
</tbody>
</table>

<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
Comments