Last active
December 9, 2019 09:48
-
-
Save yairEO/682d87c1c682b503673b25cb07daa932 to your computer and use it in GitHub Desktop.
Replace text in complex DOM with a node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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