To do this you will need to walk the DOM and understand how to process the individual nodes.
The basic walk code is this:
function walk(root)
{
if (root.nodeType == 3) // text node
{
doReplace(root);
return;
}
var children = root.childNodes;
for (var i = children.length - 1 ; i >= 0 ; i--)
{
walk(children[i]);
}
}
The walk function checks all the children of the input node and:
- if it sees a text node it calls the replacement function
- otherwise it recursively calls itself with the child node as the new input node.
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.
The doReplace function is like this:
function doReplace(text)
{
var div = document.createElement("div");
div.innerHTML = text.nodeValue.replace(/(w+)/g, "<span>$1</span>");
var parent = text.parentNode;
var children = div.childNodes;
for (var i = children.length - 1 ; i >= 0 ; i--)
{
parent.insertBefore(children[i], text.nextSibling);
}
parent.removeChild(text);
}
This creates a container node, then applies the regex and uses innerHTML to parse the result into a DOM fragment. The children of the div
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.
Finally, the change can be applied by calling the walk function.
e.g.
window.onload = function() { walk(document.body); };
A complete working example can be found at http://www.alohci.net/text/html/wordwrapper.htm.ashx
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…