Friday 15 August 2008

How to add (replace) a row (tr) or a cell (td) withouth using innerHTML in IE

There is one well know restriction in MS browser called IE that makes developers life very much harder than they actually would like to have : it is not possible to add or change a row context using innerHTML property. A lot of architectural changes were done to work around this restriction and also was quite a head-ache in the project I am working on.

Fortunately I recently discovered very interesting and usefull post explaining why it is so and, what is much more important, describing a workaround that exists!! Very much appreciate to such persons!

Here is a small example demonstrating how this works.. you can go to any w3schools.com test environment, paste the code published below and see how it works)

<head>
<script type="text/javascript">
function change()
{
var temp=document.getElementById('3')
temp.innerHTML="<table><tr id='8'><td>qqq2</td><td>3qqq</td></tr></table>"

var rrr=document.getElementById('8')
var tb = document.getElementById('2');

tb.parentNode.replaceChild(rrr, tb);

}

function add()
{
var temp=document.getElementById('3')
temp.innerHTML="<table><tr id='8'><td>qqq2</td><td>3qqq</td></tr></table>"

var rrr=document.getElementById('8')
var tb = document.getElementById('2');

tb.parentNode.insertBefore(rrr, tb);
}
</script>
</head>

<body>
Choose one or another operation (cannot use both in this demo) <br /><input type="button" onclick="add()" value="Add">
<input type="button" onclick="change()" value="Change">
<table id="22" border=1>
<tr id="1"><td>2</td><td>3</td></tr>
<tr id="2"><td>2</td><td>3</td></tr>
</table>

<span id="3" style='visibility:hidden'></span>

</body>

</html>

Notice that you don't have to go need to know what is the parent of the element to be replaced or try to obtain a parent first and then find a right position of the child. It is enough to have a reference to the item to be replaced and then just get it parent by tb.parentNode and provide the element to be replaced as the function parameter (replaceChild).

4 comments:

Max Graham said...

all you need is a TBODY element.

See the IE bug (and workaroud) here:

http://webbugtrack.blogspot.com/2007/12/bug-210-no-innerhtml-support-on-tables.html

Deniss said...

Not sure what do you mean saying that? having tbody will not let me use innerHTML.

Am I wrong?

Max Graham said...

If you add a tbody to your table, then stuff that tbody, with the HTML you want via myTBody.innerHTML = yourNewTableData;

then it should work in IE.

Deniss said...

Yes, I presume you are correct, but for me the most interesting part was - how to replace an individual row and, as your post says as well, replaceChild is the way