用innerhtml替换节点

Mos*_*ieh 5 html javascript dom

使用 JavaScript,我想删除特定的 DOM 节点并将其替换为 innerHTML。例如我想改变

<div>
...
   <div id="t1">
        this is <b> the text </b> I want to remain.
   </div>
...
</div>
Run Code Online (Sandbox Code Playgroud)

<div>
...
    this is <b> the text </b> I want to remain.
...
</div>
Run Code Online (Sandbox Code Playgroud)

gna*_*arf 3

尝试这个:

var oldElem = document.getElementById('t1');
oldElem.innerHTML = 'this is <b> the text </b> I want to remain.';
var parentElem = oldElem.parentNode;
var innerElem;

while (innerElem = oldElem.firstChild)
{
  // insert all our children before ourselves.
  parentElem.insertBefore(innerElem, oldElem);
}
parentElem.removeChild(oldElem);
Run Code Online (Sandbox Code Playgroud)

这里有一个演示。

这实际上与 jQuery 中的内容相同.replaceWith()

$("#t1").replaceWith('this is <b> the text </b> I want to remain.');
Run Code Online (Sandbox Code Playgroud)