Saturday, November 24, 2007

Javascript Revisit 2 - IE needs TBODY!

This had been bugging me for an hour and I just couldn't get it work until... I remind of my previous framework's similar situation.

It was the IE TABLE structure, IE DOM will always needs a TBODY for TABLE's body, so this code actually works on Firefox, but not IE:

var tbl=document.createElement("TABLE");
var tr=document.createElement("TR");
var td=document.createElement("TD");
tbl.appendChild(tr);
tr.appendChild(td);
td.innerHTML="You see me!";
document.getElementById("somedivID").appendChild(tbl);

Well, it works perfectly in Firefox, but when executed in IE, there's no error too, but also, there's nothing being displayed in the somedivID's DIV. However, if you do an inspection like this:

var eleDiv=document.getElementById("somedivID");
alert(eleDiv.innerHTML);

This will display the table's code correctly and you'll like me, start scratching your head on what is going on? and then you colleague will tell you to post to MSDN forum and try to get help from there.

Well.. the truth is... as there's something missing, that's TBODY for the TABLE.

var tbl=document.createElement("TABLE");
var tblbody=document.createElement("TBODY");
var tr=document.createElement("TR");
var td=document.createElement("TD");
tbl.appendChild(tblbody);
tblbody.appendChild(tr);
tr.appendChild(td);
td.innerHTML="You see me!";
document.getElementById("somedivID").appendChild(tbl);

And voila, this works.

Hope this helps if you encounter the same issue.

regards,
choongseng

No comments: