Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and Highlight in jQuery

Tags:

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 https://raw.github.com/bartaz/sandbox.js/master/jquery.highlight.js to enclose searched content inside span. But only div3 is highlighted. Please help.

like image 913
praveen Avatar asked Nov 01 '13 04:11

praveen


People also ask

How do I highlight text in HTML using jQuery?

<mark/> tag is a html 5 element used to highlight the text. Thats it. Hope this small code snippet will help you for achieving highlighting text using jQuery.

How do you highlight text in JavaScript?

Highlight Text Using the Mark Tag Method in JavaScriptIf you surround any text inside the mark tag, the browser will automatically highlight it in a striking yellow color. This will make highlighting a searched text quite a simple task then.

How do you highlight text in HTML CSS?

How Do I Highlight Text In CSS? To Highlight text in HTML you have to use an inline element such as the <span> element and apply a specific background style on it. This will create the highlighting effect, which you can tweak in many different ways to create different looks.


1 Answers

http://jsfiddle.net/UPs3V/291/

 var src_str = $("#test").text(); 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");  $("#test").html(src_str); 

try this one it may help you

like image 197
sarath Avatar answered Sep 20 '22 19:09

sarath