Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've adapted the following from my answers to several similar questions on SO (<a href="https://stackoverflow.com/a/5905413/96100">example</a>). It's designed to be reusable and has proved to be so. It traverses the DOM within a container node you specify, searching each text node for the specified text and using DOM methods to split the text node and surround the relevant chunk of text in a styled <code>&lt;span&gt;</code> element.</p> <p>Demo: <a href="http://jsfiddle.net/HqjZa/" rel="nofollow noreferrer">http://jsfiddle.net/HqjZa/</a></p> <p>Code:</p> <pre><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 &amp;&amp; (result = regex.exec(textNode.data)) ) { matchedTextNode = textNode.splitText(result.index); matchedText = result[0]; matchLength = matchedText.length; textNode = (matchedTextNode.length &gt; 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"); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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