1

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.

Community
  • 1
  • 1

2 Answers2

5

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);
RobG
  • 142,382
  • 31
  • 172
  • 209
  • this answer and xavi's works well, though can it be amended to work with links if the contains a links or images inside it. Probably cause its creating a textnode but using innerHTML in replace inputs links in their full .... format. –  Oct 30 '11 at 21:54
  • If the selection includes markup that you want to keep, then use innerHTML. However, you should not be wrapping arbitrary markup in span elements as only a limited set of other elements may appear as child nodes of span elements. Also, the selection may start inside one element and end inside another, you can't simply wrap that in a span. – RobG Oct 31 '11 at 00:56
1

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)

Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • Don't use innerHTML, use textContent or innerText as appropriate. – RobG Oct 30 '11 at 21:05
  • @RobG Could you please explain why? – lc2817 Oct 30 '11 at 21:27
  • 1
    Because innerHTML will return any internal HTML also, whereas the textContent and innerText properties only return text. If the content is supposed to be only text, then the most appropriate property to use is the one that only returns text. – RobG Oct 31 '11 at 00:52