Created
February 16, 2011 19:18
-
-
Save peterbraden/829960 to your computer and use it in GitHub Desktop.
Highlight words in html with a jquery plugin using jquery methods rather than raw DOM.
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
/* | |
* HTML Highlighter | |
*/ | |
(function($){ | |
$.fn.highlight = function(words, options){ | |
var elements = $(this) | |
, settings = { | |
className: 'highlight' | |
, caseSensitive: false | |
} | |
, term = function(x){ | |
if (!settings.caseSensitive) | |
return x.toLowerCase() | |
return x | |
} | |
$.extend(settings, options || {}) | |
if (typeof words === 'string') | |
words = [words] | |
$.each(elements, function(){ | |
var $element = $(this).children().highlight(words) | |
$.each(words, function(i, word){ | |
word = term(word) | |
$element | |
.contents() | |
.filter(function(){ // Text node && matches | |
return this.nodeType === 3 && term(this.data).indexOf(word) > -1 | |
}) | |
.each(function(){ | |
var ind = term(this.data).indexOf(word) | |
, len = word.length | |
, pre = $('<span />').text(this.data.substring(0, ind)) | |
, text = $('<span />') | |
.text(this.data.substring(ind, ind + len)) | |
.addClass(settings.className) | |
, post = $('<span />').text(this.data.substring(ind+len)) | |
$(this).replaceWith(pre.after(text).after(post)) | |
}) | |
}) | |
}) | |
return elements | |
} | |
}(jq)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment