Skip to content

Instantly share code, notes, and snippets.

@liudongmiao
Last active December 7, 2018 11:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liudongmiao/16a9ccb64bd7d1e1d808e6b8deb65db8 to your computer and use it in GitHub Desktop.
Save liudongmiao/16a9ccb64bd7d1e1d808e6b8deb65db8 to your computer and use it in GitHub Desktop.
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