Tuesday, September 25, 2007

Dynamic Table in IE


Problem

Display a dynamic table with in a <div> tag in IE using Javascript.

Non-working Solution

var divElement = document.getElementById("divId");

var tableElement = document.createElement("table");
tableElement.setAttribute("width", "100%");
var tableNode = divElement.appendChild(tableElement);

var trElement = document.createElement("tr");
var tdElement = document.createElement("td");
var trSubGroup = trSubGroup.appendChild(trElement);
var tdFirst = trSubGroup.appendChild(tdElement);
var textNode = document.createTextNode('text');
tdFirst.appendChild(textNode);

This snippet looks all good to display the table, but guess what, it works in Firefox but not in IE.

After a bit of looking around, I found the solution and the cause. IE does not recognize table which does not have <tbody> tag as the child node of <table>. Here, since we are creating dynamic table we have to include the <tbody> tag explicitly. Important to note is that for static tables IE automatically adds the <tbody> tag.

Working Solution

So, the revised code would look like this:

var divElement = document.getElementById("divId");
var tableElement = document.createElement("table");
tableElement.setAttribute("width", "100%");
var tableNode = divElement.appendChild(tableElement);

var tBodyNode = document.createElement("tbody");
var tbody = tableNode.appendChild(tBodyNode);

var trElement = document.createElement("tr");
var tdElement = document.createElement("td");
var trSubGroup = tbody.appendChild(trElement);
var tdFirst = trSubGroup.appendChild(tdElement);
var textNode = document.createTextNode('text');
tdFirst.appendChild(textNode);

No comments: