Skip to content

Instantly share code, notes, and snippets.

@ppazos
Created July 9, 2017 15:00
Show Gist options
  • Save ppazos/341573c0da60f4ca65b8bc0b1af799ee to your computer and use it in GitHub Desktop.
Save ppazos/341573c0da60f4ca65b8bc0b1af799ee to your computer and use it in GitHub Desktop.
/*
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