Created
July 19, 2013 05:37
-
-
Save sivagao/6036887 to your computer and use it in GitHub Desktop.
text replacement with javascript. for example add <span class="searhterm"> for search result.
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
/* | |
Progress: | |
Essentially, the right way to do it is… | |
Iterate over all text nodes. | |
Find the substring in text nodes. | |
Split it at the offset. | |
Insert a span element in between the split. | |
*/ | |
matchText(document.getElementsByTagName('artcle')[0], new RegExp("\\b" + saerchTerm + "\\b",'g'), function(){ | |
function(node, match, offset){ | |
var span = document.createElement('span'); | |
span.className = 'search-term'; | |
span.textContent = match; | |
node.parentNode.insertBefore(span, node.nextSibling); | |
} | |
}); | |
var matchText = function(node, regex, callback, excludeElements) { | |
excludeElements || (excludeElements = ['script', 'style', 'iframe', 'cavas']); | |
var child = node.firstChild; | |
do { | |
switch (child.nodeType) { | |
case 1: | |
if (excludeElements.indexOf(child.tagName.toLowerCase()) > -1) { | |
continue; | |
} | |
matchText(child, regex, callback, excludeElements); | |
break; | |
case 3: | |
child.data.replace(regex, function(all) { | |
var args = [].slice.call(arguments), | |
offset = args[args.length - 2], | |
newTextNode = child.splitText(offset); | |
newTextNode.data = newTextNode.data.substr(all.length); | |
callback.apply(window, [child].concat(args)); | |
child = newTextNode; | |
}); | |
break; | |
} | |
} while (child = child.nextSibling); | |
return node; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment