Skip to content

Instantly share code, notes, and snippets.

@newtonapple
Created October 2, 2010 03:03
Show Gist options
  • Save newtonapple/607215 to your computer and use it in GitHub Desktop.
Save newtonapple/607215 to your computer and use it in GitHub Desktop.
function highlightText(node, text) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(text.toUpperCase());
console.log(node.data);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
spannode.style.backgroundColor = 'yellow'
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(text.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], text);
}
}
return skip;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment