Here is what I came up with: http://jsfiddle.net/c24w/cZegf/
HTML
<ul id="test"> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam lorem tincidunt mauris eu Lorem risus.</li> <li>Vestibulum auctor dapibus neque.</li> </ul>
Js
$('li', '#test').each(function highlightElement(i, e) { e = $(e); e.html(e.html().replace(/lorem/gi, function handleMatch(match) { if (!e.hasClass('look-at-me')) e.addClass('look-at-me'); return '<match>' + match + '</match>'; })); });
CSS
.look-at-me { background: #f00; } match { background: #ff0; }
Info
Regular expression:
/lorem/gi ↑↑ ||_ case-insensitive |_ matches multiple (global)
Match Function:
handleMatch(match) - every successful regular expression handleMatch(match) is passed to this function, where the matched text is surrounded by <match></match> . This implementation makes it easy to change the exact pattern you want to highlight, since only the regular expression needs to be updated. In addition, if necessary, the parent match element is highlighted.
source share