Created
July 9, 2017 15:00
-
-
Save ppazos/341573c0da60f4ca65b8bc0b1af799ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
https://stackoverflow.com/questions/7380226/find-word-in-html | |
*/ | |
function wrapWord(el, word) | |
{ | |
var expr = new RegExp(word, "i"); | |
var nodes = [].slice.call(el.childNodes, 0); | |
for (var i = 0; i < nodes.length; i++) | |
{ | |
var node = nodes[i]; | |
if (node.nodeType == 3) // textNode | |
{ | |
var matches = node.nodeValue.match(expr); | |
if (matches) | |
{ | |
var parts = node.nodeValue.split(expr); | |
for (var n = 0; n < parts.length; n++) | |
{ | |
if (n) | |
{ | |
var span = el.insertBefore(document.createElement("span"), node); | |
span.appendChild(document.createTextNode(matches[n - 1])); | |
} | |
if (parts[n]) | |
{ | |
el.insertBefore(document.createTextNode(parts[n]), node); | |
} | |
} | |
el.removeChild(node); | |
} | |
} | |
else | |
{ | |
wrapWord(node, word); | |
} | |
} | |
} | |
var container = document.createElement("div"); | |
container.style.display = "none"; | |
document.body.appendChild(container); // this step is optional | |
container.innerHTML = where; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment