6

I have a div containing some text:

<div>Some text here</div>

I also have a text box where the user will enter a search string.

Is there a CSS way to set the background-color property for a text string matching a particular keyword entered in the search field?

What I have done currently is to find and replace using JavaScript. I am ready to use jQuery for this.

Chris Spittles
  • 15,023
  • 10
  • 61
  • 85

5 Answers5

3

Found this jQuery plugin called SearchHighlight

Here is the code

CSS

<style type='text/css'>
 span.hilite {background:yellow}
</style>

JavaScript

<script src='SearchHighlight.js'></script>
<script type='text/javascript'>
  $(function(){
      $('#textBoxId').keyup(function () {
          var val = $(this).val();
          var options = {
              exact:"partial",
              style_name_suffix:false,
              keys:val
          }
          $(document).SearchHighlight(options);
      }
  });
</script>
2

enter code hereSeems like you need jQuery highlighter plug in

http://mir3z.github.io/jquery.texthighlighter/

jQuery Text Highlighter is a jQuery plugin for highlighting text fragments in HTML documents.

Note: If you need some assistance in jQuery then refer http://jquery.com/

Narendra
  • 3,069
  • 7
  • 30
  • 51
  • Not sure this is what I want. Can you help me on how to select a text in the div by clicking a button? I checked the docs, but in all I need to select the text using mouse. –  Mar 14 '14 at 11:10
1

CSS is not capable of this. Use a JS solution like you are already doing.

My research is based on data from this question CSS 3 content selector?

Community
  • 1
  • 1
Webbanditten
  • 850
  • 9
  • 21
1

Using jQuery UI you can try this

JavaScript code

$("body").highlight(searchTerm);

CSS

.highlight{background-color:yellow}
splattne
  • 102,760
  • 52
  • 202
  • 249
Arjit
  • 3,290
  • 1
  • 17
  • 18
0

You can use raw Jquery like below:

function highlight(term,text){
  let tags=text.split(term);
  $(tags).each(function(index,value) {
    tags[index]= '<span>'+value+'</span>';
  });

  return tags.join('<span class="bg-warning text-white">'+term+'</span>');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="test"></p>
<script>
  $(document).ready(function(){
    $("#test").html(highlight("search","your search term"));
  });
</script>
PouriaDiesel
  • 660
  • 8
  • 11