因此,您可以找到所有文本节点,
function forEachTextNode(f, node) {
if (node.nodeType === 3) {
f(node);
} else {
for (var child = node.firstChild, next; child; child = next) {
next = child.nextSibling; // Grab next early in case f mutates the DOM.
forEachTextNode(f, child);
}
}
}
然后拆分使用Text.splitText
来打破你想要的单词:
function forEachSubstring(f, text, textNode) {
var i = textNode.nodeValue.indexOf(text);
if (i >= 0) {
// Split before the words we want to operate on.
textNode.splitText(i);
var substringNode = textNode.nextSibling;
// Split after the words we want to operate on.
substringNode.splitText(text.length);
var rest = substringNode.nextSibling;
// Operate on the substring.
f(substringNode);
// Recurse to look for more occurrences of text.
forEachSubstring(f, text, rest);
}
}
然后将它们绑在一起:
function wrapInParagraph(node) {
var wrapper = node.ownerDocument.createElement('p');
node.parentNode.replaceChild(wrapper, node);
wrapper.appendChild(node);
}
forEachTextNode(
function (tn) { forEachSubstring(wrapInParagraph, "Hello, World", tn); },
document.body);