gpt4 book ai didi

javascript - 用 innerhtml 替换节点

转载 作者:搜寻专家 更新时间:2023-10-31 23:14:23 25 4
gpt4 key购买 nike

我想使用 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 .

这实际上与 .replaceWith() 相同来自 jQuery:

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

关于javascript - 用 innerhtml 替换节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2742869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com