Highlight piece of text using jQuery

Some guy on Stack Overflow wanted to know how to highlight a piece of text in given page using jQuery. Finding proper solution for jQuery (client-side) took me around ten seconds as three most important search results were found on StackExchange and jQuery documentation itself. Anyway, here’s a copy of my answer.

Here is an example in a very brief:

$('div:contains("This <div>is</div> <span>Text 2</span>.")')wrap("<strong class="highlight"></strong>");

It generally finds, whatever you want to find and wraps it with whatever you want it to be wrapped with. This solution works, when the text, that you want to find is inside some div container. That is why, I used div:contains selector. If you want to search whole page, you can use *:contains selector instead.

If you are using any textbox to put there, what you want to search, you can of course use something like this:

$("#mysearchbox").change(
{
    $('div:contains($("#mysearchbox")').wrap("<strong class="highlight"></strong>");
});

and define your search box somewhere else for example like this:

<input id="mysearchbox" />

Finally, define some CSS styling for highlight class to actually highlight found text.

This way, you’re attaching an onChange event to your search box, that will be fired anytime you type anything to it and that should find (and highlight) anything you entered. Note that this examples are from-hand (from memory). I don’t have access do jQuery from where I’m writing, so I can’t check, if there aren’t any mistakes, in what I’ve just wrote. You need to test it yourself.

Sources:

  1. Find text string using jQuery?.
  2. Find text using jQuery?.
  3. jQuery .wrap() method description.

Leave a Reply