3

I need to Highlight searched text when the page is loaded , the whole words that match a specific word to be highlighted .

I know I can use id of the div & accordingly highlight the field .

The issue here that I have a complex structure of div
I have found this over Google but this works over "p:"

 var str = "test";
      $(function(){
           $('p:contains('+str+')').
               each(function(){
                 var regex = new RegExp(str, "g");
                 $(this).html(
                     $(this).html().
                         replace( regex ,
                                 "<span class='highlight'>"+str+"</span>"
                                )
               );
           });
     });

I have tried to mess with this code to loop over div instead , but I couldn't reach a solution

Sreekumar P
  • 5,900
  • 11
  • 57
  • 82
Echo
  • 2,959
  • 15
  • 52
  • 65
  • Only use `html` if you know what you are doing. It will destroy and create the DOM elements which means that you will loose e.g. event handlers. Have a look at [this plugin](https://github.com/fkling/jquery_playground/blob/master/jquery_text_highlight.js) I created for a similar question. – Felix Kling Jul 10 '11 at 14:39

5 Answers5

3

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free, open-source developed by me on GitHub (project reference).

dude
  • 5,678
  • 11
  • 54
  • 81
0

I have found an answer to my solution here .

Echo
  • 2,959
  • 15
  • 52
  • 65
-1

This JQuery Highlight Plugin offers some extra options (like searching for whole words only as requested by the OP) and is very simple to use.

I'm using it as

$(".materia").highlight($('#tbxBusca').val());

to highlight text typed into a textbox.

marquito
  • 885
  • 11
  • 29
-1

I created a plugin based on the plugin mentioned by @Echo. The advantage with this version is that it allows you to "highlight a bunch of words at once."

It is intended to work like the goggle highlight where you pass it a search string and it finds occurrences of those words and highlights them.

You can pick it up here

isaac
  • 631
  • 1
  • 5
  • 10
  • 1
    When I follow what very limited instructions you show on your plugin, I just get `.js` errors (tried several different ways), so I can only assume that it is not set up correctly. When I do it the way you've shown on your site, I just get that whatever element I target doesn't have the method "easyMark". I like the premise behind this plugin, but I can only assume that it no longer works, if it ever did. – VoidKing Nov 01 '13 at 14:34
-2

To highlight multiple text use this modified highlight.js

https://github.com/tankchintan/highlight-js

Usage:

<!DOCTYPE html>
    <html>
    <head>
      <script src="jquery.js" type="text/javascript"></script>
      <script src="highlight.js" type="text/javascript"></script> <!-- https://github.com/tankchintan/highlight-js -->
      <script>
      function highlightme()
      {
        var str=document.getElementById('search').value;
        var strarray=str.split(" ");
        void($('#content').removeHighlight().highlight(n)); //pass string array to function
      }
      </script>
      <style type="text/css">
        .highlight{ background-color:yellow; }
      </style>
    </head>
    <body >
        <input type="text" name="search" id="search" onblur="highlightme()" />
        <div id="content">Highlight Highlight Test Multiple</div>
        <a href="JavaScript:$('#content').removeHighlight();">Clear highlight</a>
    </body>
    </html>
Baskaran
  • 1,989
  • 1
  • 11
  • 6