Last active
August 29, 2015 13:57
-
-
Save MadeByMike/9383620 to your computer and use it in GitHub Desktop.
This file contains 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
// 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