1

I'm trying to iterate a set of textNodes and replacing some occurrences with an HTML element.

For example:

<span>some text<br>without html nodes</span>

Translates to

  • Node1: Type Text "some text"
  • Node2: Type Element: <br>
  • Node3: Type Text: "without html nodes"

How do I modify for example node 3 into:

  • Node3: Type Text "without"
  • Node4: Type Element <span>html</html>
  • Node5: Type Text "nodes"

So, basically I want to replace a substring of a textnode and convert it into an html node. Any ideas?

6
  • span.innerHTML = span.innerHTML.replace('html','<span>html</span>') Commented Oct 5, 2016 at 14:02
  • are the values of Node 1, 2, 3, 4, 5 a constant string or its a variable ? Commented Oct 5, 2016 at 14:03
  • maybe show how you get those textnodes Commented Oct 5, 2016 at 14:03
  • I m getting the nodes through element.childNodes Commented Oct 5, 2016 at 14:13
  • @adeneo With your suggestion, If there are two or more instances of "html" in the text, they will also be replaced. I'm relying on the index positions and lengths. Commented Oct 5, 2016 at 14:41

1 Answer 1

4

The Range interface provides a lot of convenient node slicing and splicing operations

let span = document.createElement("span")
span.insertAdjacentHTML("afterbegin", "some text<br>without html nodes") 
let text = span.childNodes[2]
let range = new Range()
range.setStart(text, 8)
range.setEnd(text, 12)
range.surroundContents(document.createElement("span"))
console.log(span.outerHTML) // prints <span>some text<br>without <span>html</span> nodes</span>

To compute the particular offsets in the text node you can use various string or regexp methods.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.