开发者

How do I replace a child DOM element with a table, compatible with internet explorer?

I'm trying to figure out how to modify the DOM to replace an element with a table. The following code shows a snafu I ran into: if I try to replace an element with a simple paragraph it works fine, but if I try to use a table then nothing shows up in Internet Explorer 8, although other browsers still work. How can I rewrite the code to make it work across all browsers?

HTML:

<p>
<a onclick="replaceElementTest(this);">Replace this text</a>
</p>

<p>
<a onclick="replaceWithTableTest(this);"&g开发者_运维问答t;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);
}


Internet Explorer has some issues with Tables. Most of the elements used in a table are actually read-only and that might be causing some of the issues you're seeing. In a project I worked on I ended up replacing all of my tables with CSS tables to get around the limitation.

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

Some docs refer to using the "Table Object Model" to do manipulation.

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


Thanks to Erik Noren for sharing this link:

Note Internet Explorer requires that you create a tBody element and insert it into the table when using the DOM. Since you are manipulating the document tree directly, Internet Explorer does not create the 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜