I adapted the following of my answers to several similar questions about SO ( example ). It is intended for reuse and has proven its worth. It traverses the DOM in the node container that you specify by looking at each node text for the specified text and using the DOM methods to separate the node text and the surrounding piece of text in the <span> style.
Demo: http://jsfiddle.net/HqjZa/
the code:
// Reusable generic function function surroundInElement(el, regex, surrounderCreateFunc) { // script and style elements are left alone if (!/^(script|style)$/.test(el.tagName)) { var child = el.lastChild; while (child) { if (child.nodeType == 1) { surroundInElement(child, regex, surrounderCreateFunc); } else if (child.nodeType == 3) { surroundMatchingText(child, regex, surrounderCreateFunc); } child = child.previousSibling; } } } // Reusable generic function function surroundMatchingText(textNode, regex, surrounderCreateFunc) { var parent = textNode.parentNode; var result, surroundingNode, matchedTextNode, matchLength, matchedText; while ( textNode && (result = regex.exec(textNode.data)) ) { matchedTextNode = textNode.splitText(result.index); matchedText = result[0]; matchLength = matchedText.length; textNode = (matchedTextNode.length > matchLength) ? matchedTextNode.splitText(matchLength) : null; surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true)); parent.insertBefore(surroundingNode, matchedTextNode); parent.removeChild(matchedTextNode); } } // This function does the surrounding for every matched piece of text // and can be customized to do what you like function createSpan(matchedTextNode) { var el = document.createElement("span"); el.style.backgroundColor = "yellow"; el.appendChild(matchedTextNode); return el; } // The main function function wrapText(container, text) { surroundInElement(container, new RegExp(text, "g"), createSpan); } wrapText(document.body, "selected here");
Tim down
source share