Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To do this you will need to walk the DOM and understand how to process the individual nodes.</p> <p>The basic walk code is this:</p> <pre><code>function walk(root) { if (root.nodeType == 3) // text node { doReplace(root); return; } var children = root.childNodes; for (var i = children.length - 1 ; i &gt;= 0 ; i--) { walk(children[i]); } } </code></pre> <p>The walk function checks all the children of the input node and:</p> <ul> <li>if it sees a text node it calls the replacement function</li> <li>otherwise it recursively calls itself with the child node as the new input node.</li> </ul> <p>Note that because the code in-place replaces nodes, the "children" node list will be affected by the replacement. To avoid this affecting the algorithm, the children are visited in reverse order.</p> <p>The doReplace function is like this:</p> <pre><code>function doReplace(text) { var div = document.createElement("div"); div.innerHTML = text.nodeValue.replace(/\b(\w+)\b/g, "&lt;span&gt;$1&lt;/span&gt;"); var parent = text.parentNode; var children = div.childNodes; for (var i = children.length - 1 ; i &gt;= 0 ; i--) { parent.insertBefore(children[i], text.nextSibling); } parent.removeChild(text); } </code></pre> <p>This creates a container node, then applies the regex and uses innerHTML to parse the result into a DOM fragment. The children of the <code>div</code> element can then replace the text node in the document. Again the moving of the nodes is done in reverse order so that the mutation of the source node list doesn't affect the loop.</p> <p>Finally, the change can be applied by calling the walk function.</p> <p>e.g.</p> <pre><code>window.onload = function() { walk(document.body); }; </code></pre> <p>A complete working example can be found at <a href="http://www.alohci.net/text/html/wordwrapper.htm.ashx" rel="nofollow">http://www.alohci.net/text/html/wordwrapper.htm.ashx</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload