Created
June 23, 2009 14:48
-
-
Save neerajsingh0101/134572 to your computer and use it in GitHub Desktop.
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
| 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