移除已包装在标签中的元素。

huangapple go评论56阅读模式
英文:

Selected text remove element already wrapped in a span

问题

2. I bold and it gets wrapped with a span

这是虚拟 文本以进行选择

<h2 这是虚拟 <span style="font-weight: 700;">文本以进行选择</span></h2>

3. 现在假设我想选择一些文本,但我们知道它已经包裹在一个 span 中

这是 虚拟 [加粗]文本[加粗] 以进行选择

4. 这是选定文本与已包含 span 的交叉点,因此我的代码。在我的重要注释中,我可以确定已找到选择中的元素。但如何找到并移除这个 span。

const el = document.createElement('span');

  function handleNodeWrap(){
    if(selection?.containsNode(el,true)){
      //! 重要:找到并移除所选文本的元素
    }
    surroundSelection(el);
  }
英文:

I have a scenario/dilemma, I am a little stuck trying to figure out. Below will be my best of a visual representation.

1. I select

This is dummy text to select

2. I bold and it gets wrapped with a span

This is dummy text to select

<h2 This is dummy <span style="font-weight: 700;">text to select</span></h2>

3. Now lets say I want to select some text but we know it's already wrapped in a span

This is dummy [BOLD]text[BOLD] to select

4. Its a crossover with selected text, so now my code. In my important comment, I can identify that the element is found in the selection. But how can I find it and then remove the span.

const el = document.createElement('span');

  function handleNodeWrap(){
    if(selection?.containsNode(el,true)){
      //! IMPORTANT find and remove element of selected text
    }
    surroundSelection(el);
  }

答案1

得分: 1

这是一个移除所选文本中的span元素的方法:

const el = document.createElement('span');

function handleNodeWrap() {
  if (selection?.containsNode(el, true)) {
    // 找到所选文本的父节点
    let parentNode = selection.anchorNode.parentNode;
    // 创建一个新的范围,选择父节点的整个内容
    let range = document.createRange();
    range.selectNodeContents(parentNode);
    // 用纯文本版本替换父节点的内容
    let text = range.extractContents().textContent;
    parentNode.textContent = text;
  } else {
    surroundSelection(el);
  }
}

<!-- 结束片段 -->

英文:

Here's one approach to remove the span from the selected text:

const el = document.createElement(&#39;span&#39;);

function handleNodeWrap() {
  if (selection?.containsNode(el, true)) {
    // find parent node of the selected text
    let parentNode = selection.anchorNode.parentNode;
    // create a new range that selects the entire content of the parent node
    let range = document.createRange();
    range.selectNodeContents(parentNode);
    // replace the content of the parent node with the plain text version
    let text = range.extractContents().textContent;
    parentNode.textContent = text;
  } else {
    surroundSelection(el);
  }
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月8日 14:54:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定