删除身体标签内的span标签

时间:2020-10-10 14:47:42

标签: javascript html

所以,我有以下html:

<p>
I wanna remove this <span class="highlight1">highlight</span> when user selects text 
and presses a button. This shouln't remove the following <span class="highlight1">highlight</span>.
</p>

当用户选择文本并执行某些操作(例如,按下按钮)时,我希望该特定文本不突出显示。我不知道如何使用香草JS :( 当文本选择位于突出显示的文本上时,我只有以下JS代码可以捕获:

//Assume code is within an event handler...
var text_selection = window.getSelection();

if (text_selection.anchorNode.parentNode.className === 'highlight1')
{
  //unhighlight
  console.log("unhighlight");
}

1 个答案:

答案 0 :(得分:1)

如果<span class="highlight1">...</span>始终只包含文本且没有其他标记,则可以通过将<span>元素替换为创建的文本节点来“删除”突出显示,将<span>元素替换为(-> .replaceWith()根据{{​​1}}

的内容 该示例中的

span将是您的伪代码中的text_selection.anchorNode.parentNode

const textNode = document.createTextNode(span.textContent);
span.replaceWith(textNode);

示例:

/* setTimeout so you can "see" the removal */
setTimeout(() => {
  document.querySelectorAll(".highlight1").forEach(span => {
    const textNode = document.createTextNode(span.textContent);
    span.replaceWith(textNode);
  })
}, 2000);
.highlight1 { color: red }
<p>
I wanna remove this <span class="highlight1">highlight</span> when user selects text 
and presses a button. This shouln't remove the following <span class="highlight1">highlight</span>.
</p>