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); }
source share