Skip to content

Instantly share code, notes, and snippets.

@peterbraden
Created February 16, 2011 19:18
Show Gist options
  • Save peterbraden/829960 to your computer and use it in GitHub Desktop.
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.
/*
* 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