How to replace a child DOM with a table compatible with Internet Explorer?

I am trying to figure out how to change the DOM to replace an element with a table. The following code shows the snafu I came across: if I try to replace an element with a simple paragraph, it works fine, but if I try to use a table, nothing will appear in Internet Explorer 8, although other browsers still work. How can I rewrite the code so that it works in all browsers?

HTML:

<p> <a onclick="replaceElementTest(this);">Replace this text</a> </p> <p> <a onclick="replaceWithTableTest(this);">Replace with test table</a> </p> 

JavaScript:

 // Works in all browsers function replaceElementTest(domElement){ var p = document.createElement("p"); p.innerHTML = "This element got REPLACED!"; domElement.parentNode.replaceChild(p,domElement); } // Doesn't work in IE8 function replaceWithTableTest(domElement){ var table, tr, td; table = document.createElement("table"); tr = document.createElement("tr"); td = document.createElement("td"); td.innerHTML = "This element got replaced by a TABLE!" table.appendChild(tr); tr.appendChild(td); domElement.parentNode.replaceChild(table,domElement); } 
+4
source share
2 answers

Thanks Eric Noren for sharing this link :

Note In Internet Explorer, you need to create a tBody element and insert it into the table when using the DOM. Because you manipulate the document tree directly, Internet Explorer does not create tBody , which is automatically implied when using HTML.

This revised JavaScript code works in IE8:

 function replaceWithTableTestA(domElement){ var table, tBody, tr, td; table = document.createElement("table"); tBody = document.createElement("tbody"); tr = document.createElement("tr"); td = document.createElement("td"); table.appendChild(tBody); tBody.appendChild(tr); tr.appendChild(td); td.innerHTML = "This element got replaced by a TABLE!" domElement.parentNode.replaceChild(table,domElement); } 
+1
source

Internet Explorer has some problems with tables. Most of the elements used in the table are actually read-only, and this may cause some of the problems you see. In the project I was working on, I replaced all of my tables with CSS tables to get around the limitation.

http://support.microsoft.com/kb/239832

Some documents cite the use of the "Table Object Model" to perform manipulations.

http://msdn.microsoft.com/en-us/library/ms532998(VS.85).aspx

+2
source

All Articles