Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
highlight word
function highlightWord(root, word, className) {
// base on https://stackoverflow.com/a/10730063
// word is lower-case
var walker, textNodes = [];
walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode: function (node) {
if (node.nodeType === Node.TEXT_NODE && node.textContent.toLowerCase().indexOf(word) >= 0) {
return NodeFilter.FILTER_ACCEPT;
} else {
return NodeFilter.FILTER_SKIP;
}
}
}, false);
while (walker.nextNode()) {
textNodes.push(walker.currentNode);
}
textNodes.forEach(function (node) {
var index, length, span, current, next;
length = word.length;
current = node;
while ((index = current.nodeValue.toLowerCase().indexOf(word)) > -1) {
next = current.splitText(index + length);
span = document.createElement("span");
span.className = className;
span.appendChild(current.splitText(index));
next.parentNode.insertBefore(span, next);
current = next;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.