【问题标题】:Formatting lost when using .replaceWith(textContent)使用 .replaceWith(textContent) 时格式丢失
【发布时间】:2021-03-09 06:56:35
【问题描述】:

我正在尝试将 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);
  }
}
}

【问题讨论】:

    标签: javascript html dom innerhtml replacewith


    【解决方案1】:

    您可以将容器的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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多