Novazero
Novazero

Reputation: 553

Highlighting Text Under Div Tag

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?

Upvotes: 2

Views: 6597

Answers (3)

Jonathan M
Jonathan M

Reputation: 17451

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>

Upvotes: 2

rajesh
rajesh

Reputation: 2523

<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>

Upvotes: 0

Hubro
Hubro

Reputation: 59383

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;
}

Upvotes: 2

Related Questions