Skip to content

Instantly share code, notes, and snippets.

@neerajsingh0101
Created June 23, 2009 14:48
Show Gist options
  • Select an option

  • Save neerajsingh0101/134572 to your computer and use it in GitHub Desktop.

Select an option

Save neerajsingh0101/134572 to your computer and use it in GitHub Desktop.
var highlightClass = 'hl';
function createHighlights(text, regex, node,parentn) {
if (regex.exec(text) != null) {
parentn.insertBefore(document.createTextNode(RegExp.$1),node);
highlightNode = document.createElement("span");
highlightNode.className = highlightClass;
highlightNode.appendChild(document.createTextNode(RegExp.$2));
parentn.insertBefore(highlightNode,node);
createHighlights(RegExp.$3, regex, node,parentn);
} else {
parentn.insertBefore(document.createTextNode(text),node);
}
}
function highlightWord(node, word) {
var wordRegex = new RegExp('(.*?)\\b(' + word + ')\\b(.*)', 'i');
if (node.nodeType == 3 && wordRegex.test(node.nodeValue)) { // text node
var parentn = node.parentNode;
createHighlights(node.nodeValue, wordRegex,node,parentn);
parentn.removeChild(node);
} else if (node.hasChildNodes()) {
var childNodes = node.childNodes;
for (var i=0; i<childNodes.length; ++i) {
var next_node = childNodes[i];
if (next_node.parentNode.className != highlightClass){
highlightWord(next_node, word);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment