[英]removing span tag within body tag
So, I have the following 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>
When user selects text and does some action (eg pressing a button), I want that specific text to be unhighlighted.当用户选择文本并执行某些操作(例如按下按钮)时,我希望不突出显示该特定文本。 I can't figure out how to do this with vanilla JS:( I only have the following JS code to capture when the text selection is on a highlighted text:
我无法弄清楚如何使用 vanilla 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");
}
If the <span class="highlight1">...</span>
will always only contain text and no other markup then you can "remove" the highlighting by replacing (-> .replaceWith()
) the <span>
element with a text node created from the content of the <span>
如果
<span class="highlight1">...</span>
将始终仅包含文本而没有其他标记,那么您可以通过替换 (-> .replaceWith()
) <span>
元素来“删除”突出显示从<span>
的内容创建的文本节点
span
in the example would be the text_selection.anchorNode.parentNode
from your pseudo code.示例中的
span
将是伪代码中的text_selection.anchorNode.parentNode
。
const textNode = document.createTextNode(span.textContent);
span.replaceWith(textNode);
Example:例子:
/* 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.