Created
June 5, 2012 15:36
-
-
Save thiyagaraj/2875764 to your computer and use it in GitHub Desktop.
Highlight text in a webpage based on keywords
This file contains hidden or 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
keywords = ['hello world','goodbye cruel world']; | |
function replaceKeywords (domNode) { | |
if (domNode.nodeType === Node.ELEMENT_NODE) { // We only want to scan html elements | |
var children = domNode.childNodes; | |
for (var i=0;i<children.length;i++) { | |
var child = children[i]; | |
// Filter out unwanted nodes to speed up processing. | |
// For example, you can ignore 'SCRIPT' nodes etc. | |
if (child.nodeName != 'EM') { | |
replaceKeywords(child); // Recurse! | |
} | |
} | |
} | |
else if (domNode.nodeType === Node.TEXT_NODE) { // Process text nodes | |
var text = domNode.nodeValue; | |
// This is another place where it might be prudent to add filters | |
for (var i=0;i<keywords.length;i++) { | |
var match = text.indexOf(keywords[i]); // you may use search instead | |
if (match != -1) { | |
// create the EM node: | |
var em = document.createElement('EM'); | |
// split text into 3 parts: before, mid and after | |
var mid = domNode.splitText(match); | |
mid.splitText(keywords[i].length); | |
// then assign mid part to EM | |
mid.parentNode.insertBefore(em,mid); | |
mid.parentNode.removeChild(mid); | |
em.appendChild(mid); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment