如何解决使用 .replaceWith(textContent) 时格式丢失
我正在尝试将 div“上移”一个级别并摆脱块引用。正如您在 this fiddle 中看到的,当您点击“更改”时,粗体字体不会被保留。我也尝试过使用 innerHTML 和 innerText 而不是 textContent 但都没有奏效。这是 HTML:
<html>
<div id="outerdiv">
<blockquote><div id="innerdiv"><b>Hello </b>Text 1</div></blockquote>
</div>
<span onclick="removeblockquotes(this)">Change</span>
</html>
还有 JS:
function removeblockquotes(e)
{for (const b of document.querySelectorAll('blockquote')) {
if (!b.closest('div')?.parentElement.closest('div')) {
b.replaceWith(b.textContent);
}
}
}
解决方法
您可以将容器的 outerHTML
设置为 innerHTML
容器,从而移除容器但保留其中的标记:
for (const b of document.querySelectorAll('blockquote')) {
if (!b.closest('div')?.parentElement.closest('div')) {
b.outerHTML = b.innerHTML;
}
}
<html>
<div id="outerdiv">
<blockquote>
<div id="innerdiv"><b>Hello </b>Text 1</div>
</blockquote>
</div>
另一种保留侦听器的方法,通过迭代子项并附加每个子项:
for (const b of document.querySelectorAll('blockquote')) {
if (!b.closest('div')?.parentElement.closest('div')) {
while (b.children.length) b.insertAdjacentElement('afterend',b.children[0]);
b.remove();
}
}
<html>
<div id="outerdiv">
<blockquote>
<div id="innerdiv"><b>Hello </b>Text 1</div>
</blockquote>
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。