-
-
Save looping84/c9e5be2f3309bcd3c79354683f8ae59e 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