blogccasion

Dynamically created tables in Internet Explorer

Spread Firefox Logo
Dynamically created tables in Internet Explorer

A weird behavior of Internet Explorer almost made me go up the wall: imagine you want to dynamically create a table in an (X)HTML document. A straight-forward implementation of this feature might look like this:

<html>
<head>
<script type="text/javascript">
function createTable() {
var table=document.createElement("table");
var tr=document.createElement("tr");
var td=document.createElement("td");

td.appendChild(document.createTextNode("Some Text"));
tr.appendChild(td);
table.appendChild(tr);

document.getElementById("aDiv").appendChild(table);
}
</script>
</head>
<body>
<div id="aDiv">
<input type="button" onclick="createTable()" value="Create Table">
</div>
</body>
<html>


In Firefox this just works the way you would have expected it to work: you click the button and a table is created. In Internet Explorer however, you click the button and nothing happens. No error message, nothing. Using the Internet Explorer Developer Toolbar, you see that the table actually appears in the DOM tree, i.e. it is there, the table gets created. So why does the browser not display it? The solution is simple. Maybe too simple. In HTML 4, all table elements can contain the thead, tfoot and tbody element. The idea behind this is to group a table into logic units. When printing a large table for example, a smart browser could include the thead and tfoot element on each page in order to simplify orientation on the printed sheets. This element however is rarely used, and the described feature is even less implemented.
To make a long story short, in order to dynamically create tables in Internet Explorer, you need to (at least) create the tbody element. The following snippet shows you how:

<html>
<head>
<script type="text/javascript">
function createTable() {
var table=document.createElement("table");
var tr=document.createElement("tr");
var td=document.createElement("td");
var tbody=document.createElement("tbody");

td.appendChild(document.createTextNode("Some Text"));
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);

document.getElementById("aDiv").appendChild(table);
}
</script>
</head>
<body>
<div id="aDiv">
<input type="button" onclick="createTable()" value="Create Table">
</div>
</body>
<html>


Hope this saves you some time…

Image from spreadfirefox.org