2

Lets say I have a div like this:

<div id="test" class="sourcecode">
"Some String"
</div>

Is it possible to have css and js to highlight a portion of that string based on a search query?

Like if I was searching for the word Stri it would just highlight that part?

Novazero
  • 553
  • 6
  • 24

3 Answers3

2

You'll have to divide the text, separating the highlighted part into a <span>. Like this.

<div id="test" class="sourcecode">
"Some <span style="background-color:yellow">Stri</span>ng"
</div>

To do characters that represent HTML tags, if you have:

<div id="test" class="sourcecode">
    &lt;html&gt;String&lt;/html&gt;
</div>

...you can highlight the same way as before:

<div id="test" class="sourcecode">
    <span style="background-color:yellow">&lt;html&gt;Stri</span>ng&lt;/html&gt;
</div>
Jonathan M
  • 17,145
  • 9
  • 58
  • 91
2

Try the jquery.highlight plugin.

Make a jQuery selector containing the div in which you want to highlight some text:

var $div = $('#test');

Then run the highlight plugin with the word(s) you wish to highlight

$div.highlight('Stri');

Also you should style the class "highlight" in your css, since that's the class the highlighter will give the highlighted text:

.highlight
{
    background-color: yellow;
    outline: 1px solid black;
}
Hubro
  • 56,214
  • 69
  • 228
  • 381
  • The problem that I forgot to address was how would I go about highlighting a string that has html like "string" where I want to highlight "str" part. – Novazero Feb 09 '12 at 19:04
0
<div id="test" class="sourcecode">
"Some String"
</div>

in javascript after getting search result.

<script>
  var test = $('test').innerHtml;
  var query= 'Str';
  var new_str = test.replace(query, '<font style="background:yellow;color:red;" >'+query+'</font>');
  $('test').innerHtml = new_str;
</script>
rajesh
  • 2,354
  • 1
  • 12
  • 15