Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active December 9, 2019 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/682d87c1c682b503673b25cb07daa932 to your computer and use it in GitHub Desktop.
Save yairEO/682d87c1c682b503673b25cb07daa932 to your computer and use it in GitHub Desktop.
Replace text in complex DOM with a node
function replaceTextWithNode( elm, text, replacerNode ){
var iter = document.createNodeIterator(elm, NodeFilter.SHOW_TEXT),
textnode,
idx,
maxLoops = 100,
replacedNode;
while( textnode = iter.nextNode() ){
if( !maxLoops-- ) break;
// get the index of which the tag (string) is within the textNode (if at all)
idx = textnode.nodeValue.indexOf(text);
if( idx == -1 ) continue;
replacedNode = textnode.splitText(idx)
// clean up the tag's string and put tag element instead
replacedNode.nodeValue = replacedNode.nodeValue.replace(text, '');
textnode.parentNode.insertBefore(replacerNode, replacedNode);
}
elm.normalize()
return replacedNode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment