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

<div>
...
   <div id="t1">
        this is <b> the text </b> I want to remain.
   </div>
...
</div>


<div>
...
    this is <b> the text </b> I want to remain.
...
</div>

最佳答案

试试这个:

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);

有一个演示here

这实际上与jQuery中的 .replaceWith() 相同:
$("#t1").replaceWith('this is <b> the text </b> I want to remain.');

07-24 21:10