程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 .replaceWith(textContent) 时格式丢失大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 .replaceWith(textContent) 时格式丢失?

开发过程中遇到使用 .replaceWith(textContent) 时格式丢失的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 .replaceWith(textContent) 时格式丢失的解决方法建议,希望对你解决使用 .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>

大佬总结

以上是大佬教程为你收集整理的使用 .replaceWith(textContent) 时格式丢失全部内容,希望文章能够帮你解决使用 .replaceWith(textContent) 时格式丢失所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: