Reputation: 185
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
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