Javascript 选择删除元素的标记名并将内容附加到 ParentNode

问题描述 投票:0回答:2
javascript dom parent-child
2个回答
0
投票

您需要为跨度添加事件监听器,然后替换如下内容。

document.querySelectorAll('span').forEach(sp => {
    sp.addEventListener('click', e => {
        e.target.outerHTML = e.target.innerHTML;
    });
});

0
投票

您当前方法的问题是您试图直接修改所选范围的outerHTML,这是不受支持的。相反,您应该使用范围对象的 extractContents() 方法将所选内容作为文档片段获取,从该片段中删除 元素,然后将修改后的片段插入回文档中。

<p>
  An <span class="item1">easyJet pilot</span> has told tourists that flying to
  <span class="item2">Rhodes</span> is a “terrible idea” just minutes before taking off, it has been reported, as
  <span class="item3">wildfires spread across Greece</span> journalist Gwyn Loader, who was on the flight to the
  island to report for BBC Wales Welsh-language news programme Newyddion, said
  <span class="item4">eight passengers</span> subsequently decided to disembark, including a young boy who was in tears.
</p>

<script>
  function cleanup() {
    const selObj = window.getSelection();
    const selRange = selObj.getRangeAt(0);

    // Create a new div element to hold the selected content
    const tempDiv = document.createElement('div');
    tempDiv.appendChild(selRange.cloneContents());

    // Remove span tags from the selected content
    const spanElements = tempDiv.querySelectorAll('span');
    spanElements.forEach(span => {
      const textNode = document.createTextNode(span.textContent);
      span.parentNode.replaceChild(textNode, span);
    });

    // Insert the modified content back into the document
    selRange.deleteContents();
    selRange.insertNode(tempDiv);

    // Clear the selection
    selObj.removeAllRanges();
  }

  // Example: Call the cleanup function when a span is clicked
  const spans = document.querySelectorAll('span');
  spans.forEach(span => {
    span.addEventListener('click', cleanup);
  });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.