Last active
December 7, 2018 11:43
-
-
Save liudongmiao/16a9ccb64bd7d1e1d808e6b8deb65db8 to your computer and use it in GitHub Desktop.
highlight word
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
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