If all you wanted to do was change the text to another plain text, you can directly change the contents of the text nodes. However, you want to add the <a> element. For each <a> element you want to add, you really want to add a child element. Text nodes cannot have children. Thus, for this you need to replace the text node with a more complex structure. In doing so, you will want to influence the DOM as little as possible so as not to break other scripts that rely on the current DOM structure. The easiest way to make a small impact is to replace the text node with <span> , which contains the new text nodes (the text will be divided around the new <a> ) and any new <a> elements.
The code below should do what you want. It replaces textNode with <span> , which contains new text nodes and created <a> elements. It replaces only one or more <a> elements.
function handleTextNode(textNode) { if(textNode.nodeName !== '#text' || textNode.parentNode.nodeName === 'SCRIPT' || textNode.parentNode.nodeName === 'STYLE' ) {
<input type="button" id="clickTo" value="Click to process"/> <div id="testDiv">This text should change to a link -->river<--.</div>
TreeWalker code was taken from my answer here .
source share