praveen praveen - 3 months ago 11
jQuery Question

Search and Highlight in jQuery

I would like to search and highlight text using jQuery/Java Script.

sample HTML 1:

<div id="div1"><b>Good</b> <b>Morning</b> </div>
<div id="div2">Good Evening</div>
<div id="div3">Good Morning</div>Searched String = "Good Morning"

When i search for String "Good Morning", Both the contents in div1 and div3 should get highlighted. ie. the output html should be

<div id="div1"><span class="highlight"><b>Good</b> <b>Morning</b> </span></div>
<div id="div2">Good Evening</div>
<div id="div3"><span class="highlight">Good Morning</span></div>

I have used the plugin to enclose searched content inside span. But only div3 is highlighted. Please help.


 var src_str = $("#test").html();
var term = "my text";
term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("("+term+")", "gi");

src_str = src_str.replace(pattern, "<mark>$1</mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4");


try this one it may help you