0

This is a followup question to Removing <span> tag while leaving content intact, with just javascript

If I use spans to highlight text in a page, it breaks up the content into new nodes. And then, when I remove the highlight spans using replaceChild, the nodes remain separated. I would like to have the original text merged back into a single text node, instead of three text nodes - the text before the highlighting started, the text that was previously highlighted, and the text after the highlighting ended. Is this possible to do?

Community
  • 1
  • 1
jonhopkins
  • 3,844
  • 3
  • 27
  • 39

2 Answers2

3

You could try something like

 containerElement.innerHTML = containerElement.textContent;

Not sure that will work on IE prior to 9 though because of textContent.

Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • This seems like it could work. But what about in the case where the containerElement has other children whose tags need to stay the same? Using that idea, I tried looping through while (the next node is also a text_node) and appending to a string, and then using innerHTML = the string, but I can't get it working. I don't mean to ask too much, I've just been trying to figure this out for a few hours and my brain is getting tired. – jonhopkins Nov 27 '12 at 21:53
2

Similar to Jim's suggestion but accommodates IE:

containerElement.innerHTML = containerElement.textContent || containerElement.innerText;

Or a much longer version:

var text = containerElement.textContent || containerElement.innerText;

while (containerElement.firstChild) {
    containerElement.removeChild(containerElement.firstChild);
}
containerElement.appendChild(document.createTextNode(text));

I think the first is simpler.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Selecting this as answer because it works with IE and the loop version can be used to manually stop at a certain node. Thank you RobG and Jim for your answers. I'm using this for elements with only text inside them. For reference to anyone who needs to do this on elements with other elements inside them (one of mine has a pre), containerElement.normalize() will merge adjacent text nodes and remove empty ones, and it leaves all other tags intact. – jonhopkins Nov 28 '12 at 14:03