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.
<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.
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With