admin管理员组

文章数量:1384497

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?

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?

Share Improve this question edited May 23, 2017 at 12:27 CommunityBot 11 silver badge asked Nov 27, 2012 at 21:34 jonhopkinsjonhopkins 3,8523 gold badges29 silver badges39 bronze badges 2
  • please post your code... – Bruno Sousa Commented Nov 27, 2012 at 21:38
  • You don't state if you can use jQuery or not. If so look at jQuery.unwrap ...api.jquery./unwrap – Jason L. Commented Nov 27, 2012 at 22:18
Add a ment  | 

2 Answers 2

Reset to default 3

You could try something like

 containerElement.innerHTML = containerElement.textContent;

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

Similar to Jim's suggestion but acmodates 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.

本文标签: domJavascript insert text into divStack Overflow