Skip to content

Instantly share code, notes, and snippets.

@MadeByMike
Last active August 29, 2015 13:57
Show Gist options
  • Save MadeByMike/9383620 to your computer and use it in GitHub Desktop.
Save MadeByMike/9383620 to your computer and use it in GitHub Desktop.
// I was looking to highlight words in text nodes today and came across:
// http://bartaz.github.io/sandbox.js/jquery.highlight.html
// http://johannburkard.de/
//
// Both seemed a little verbose so I came up with the solution below.
// Please note this has not yet been fully tested, but worked for my needs.
var words = ['words','to','mark'];
$.each(words, function(i, word){
mark_my_word($('#content'), word);
})
function mark_my_word($elm,word){
$.each($elm.find("*").contents().filter(function(){
return( this.nodeType === 3 );
}), function(i, node){
$(node).replaceWith(node.data.replace(RegExp("("+word+")", "ig"), "<mark>$1</mark>"));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment