RootAtKali
RootAtKali

Reputation: 185

Convert string after replace in html DOM element in the same position

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

Upvotes: 0

Views: 114

Answers (2)

Greedo
Greedo

Reputation: 3549

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>

Upvotes: 1

Mamun
Mamun

Reputation: 68933

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;

Upvotes: 1

Related Questions