0

I Have a Node from DOM, in this node I find a string and I replace it before and after with open/close span tag in this way:

   tmp(node){
    if (node.nodeType === 3) { // Node.TEXT_NODE
      var text = node.data.replace(/In eterni Dei/, "<span>In eterni Dei<span>");
      if (text != node.data)
          node.data = text;
    } else if (node.nodeType === 1) { // Node.ELEMENT_NODE
        for (var i = 0; i < node.childNodes.length; i++) {
            this.tmp(node.childNodes[i]);
        }
    }
  }

This solution work but replace only the string, I need that the replacement can convert my replaced string in HTML DOM elements in the same position

2 Answers 2

1

You can use innerHTML to read the whole HTML content at once and then do a mass replacement. changes in the innerHTML will be computed

function tmp(node){
      var text = node.innerHTML.replace(/In eterni Dei/g, "<span>In eterni Dei</span>");
      if (text != node.innerHTML)
          node.innerHTML = text;
          
      console.log(node.innerHTML)
  }
  
  tmp(document.getElementById("div"));
<div id="div">
  In eterni Dei
  <div>
    In eterni Dei
   </div>
</div>

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

Comments

1

To modify the markup you should use innerHTML property of the element:

var text = node.data.replace(/In eterni Dei/, "<span>In eterni Dei<span>");
node.innerHTML = text;

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.