Table innerHTML -- work around

[b][size=medium]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 :) [/size][/b]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值