首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > CSS >

Table innerHTML - work around

2012-11-06 
Table innerHTML -- work aroundAs many of you must have read or realised(i did) while working with i

Table innerHTML -- work around
As many of you must have read or realised(i did) while working with it, MS Internet Explorer doesn't allow you to set the innerHTML property of any table related tag(table, thead, tbody, tr except for td). It says "Unknown Runtime Exception". You are provided with explicit methods to handle this. Like createRow, createCell and stuff... Also you can use W3C DOM append child.

Good way to make tables, but what if I have the Table Head defined in the HTML file and read the Table Body from a XML file as well defined string. I simply want to have this in the table... One way is I parse the string as XML and loop through the nodes creating the cells and so on (that is what I first did), But why do we need that unecessary processing. We don't have any method to parse the string and get into our DOM directly.

The work around I worked out is probably not the only or best, but works good.

suppose we have a variable sXmlBody which has all the table body rows defined like:

var sXmlBody = "<tr><td>cellOne1</td><td>cellTwo1</td><tr>" +
"<tr><td>cellOne2</td><td>cellTwo2</td><tr>" ;


Of course it will be created dynamically ;)

Now to add this to the DOM enclose it in actual table and tbody tags.

sXmlBody = "<table><tbody>" + sXmlBody + "</tbody></table>";

and get it in DOM parsed as HTML using a temp div


var tempDiv = document.createElement("DIV");
tempDiv.innerHTML = sXmlBody;

Now I can use W3C DOM to append the child from the temp div to the table in our document. Consider the id of the table in the HTML document id tableResults


var tableElement = document.getElementById("tableResult");
tableElement.appendChild(tempDiv.firstChild.firstChild);

If you are going to reload the table content, it will be useful to have an id for the tbody tag and use removeChild on the documents table with the tbody element as parameter.

I hope that's helpful to you all, and it works fine in Firefox too!

Till Next time . . . Happy coding

热点排行