Skip to content

Instantly share code, notes, and snippets.

@thiyagaraj
Created June 5, 2012 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiyagaraj/2875764 to your computer and use it in GitHub Desktop.
Save thiyagaraj/2875764 to your computer and use it in GitHub Desktop.
Highlight text in a webpage based on keywords
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