May 1, 2011
Highlight text with jQuery
Here I am going to show how to highlight particular word within a block of text.
You can use this feature to:
– highlight the search terms on the page.
– highlight particular keywords dynamically on the page.
– highlight negative numeric values on block of page.
Below is the working example, enter the text in textbox and click on “highlight” button to highlight the text in the block.
Sample text for highlight.
Sample text for highlight1.
Let us take a the sample text
<div id="content-block">
<p>
Sample text for highlight.
</p>
<p>
Sample text for highlight1.
</p>
</div>
$(document).ready(function() {
$('input[name="hbtn"]').click(function() {
var o ={words:$('input[name="query"]').val()};
highlight("content-block", o);
});
});
here is the code for highlight the word in block of text
function highlight(id, options) {
var o = {
words: '',
caseSensitive: false,
wordsOnly: true,
template: '$1<span class="highlight">$2</span>$3'
}, pattern;
$.extend(true, o, options || {});
if (o.words.length == 0) { return; }
pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', o.caseSensitive ? "" : "ig");
$('#'+id).each(function() {
var content = $(this).html();
if (!content) return;
$(this).html(content.replace(pattern, o.template));
});
}
7 Comments
Wow, that’s really totally cool and nice code, thanx man, I learned a few things here :o)!
Hi, there seems to be a problem with your regexp expression, as it’s not finding texts after “.”
I’ve changed the pattern like this:
(>[^<]*)(' + o.words + ')([^ I’ve changed this to take a collection instead of the API in the interface, sending my own $(..) result-collection into it
– it would be nice for the others to have implemented the “wordsOnly” parameter as well
– the “options || {}” trick is pretty cool but I had hard time to find what it’s doing 🙂 – may be a short comment would have been helpful!
– ‘words’ parameter is a bit misleading, one would think it’s an array, but it seems to be only a 1-item-phrase, isn’t it?
Thank you very much for your time,
Andrej
Yes Andy, that’s true. Thank you very much for your inputs. I will update soon.
“words” is little bit misleading, should be “word”.
..one more note: for finding duplicates, the regexp expression is not sufficient. Bye, Andrej
very very veryyyyyyyyyyyyyyyyyyyyyy thank u.
if you search for t letter ,dont highlight all t.why?thank u
how can highlight in more than one element in same time?