问题
I'm doing some in page highlighting, and found the most popular example when using text selection and adding spans is by switching to designMode and running execCommand
How can I highlight the text of the DOM Range object?
There's no follow up though on how to remove the span tags once created. I saw some examples using jquery and the replaceWith, but none with straight javascript.
回答1:
You should be able to do something like:
// Where span is a reference to the span to be replaced
var text = span.textContent || span.innerText;
var node = document.createTextNode(text);
span.parentNode.replaceChild(node, span);
回答2:
Just create a new text node with the contents (innerHTML
) of the <span>
. Replace the <span>
node with replaceChild
on its parent:
spanTag.parentNode.replaceChild(document.createTextNode(spanTag.innerHTML), spanTag)
来源:https://stackoverflow.com/questions/7947763/removing-span-tag-while-leaving-content-intact-with-just-javascript