February 10, 2009

IE javascript table createElement tr not working error cells[0] undefined

In IE, if one tries to create a javascript table object followed by creation of row and cell objects it doesn't works. The document.createElement() API is not working error for Internet Explorer and one gets the cells[0] undefined error.

The complete scenario is as follows:

I recently faced this error on Internet Explorer only. I created table, rows and cells using JS as follows
----------------------------------------------------------------------------
// Utility function to create Tag in browser neutral way
function createTag(parent,tag) {
var createdTag = null;
if(isIE) {
createdTag =  document.createElement("<" + tag + ">");
} else {
createdTag  = document.createElement(tag);
}
if(parent) {
parent.appendChild(createdTag );
}
return createdTag;
}

// Code snippet that creates a Table Row and then cell inside the table row. This was failing in IE (Internet explorer)

var tblBody =document.getElementById("tblObjId");
var tr = createTag(tblBody, "tr");
var td = createTag(tr, "td");
// error was coming for this line
tr.cells[0].innerHTML = "<i>First cell</i>";
----------------------------------------------------------------------------
In IE javascript error undefined started coming when I tried to access the row cell using  tr.cells[0].
This code snippet was working well in all other browsers. The simple fix to this problem is to fix it as follows.

var tblBody =document.getElementById("tblObjId");
// 1. Create a <tbody> tag inside table object first
var tbody = createTag(tblBody, "tbody");
// 2. Create all the required rows inside the TBODY object
var tr = createTag(tbody, "tr");
var td = createTag(tr, "td");
// Now this code will work fine on any browser
tr.cells[0].innerHTML = "<i>First cell</i>";