Today, I have worked on a very simple script to search and highlight words in jquery inside HTML. Let’s get started, shall we?

Let me explain the basic logic first. The idea is to look into the browser object’s content and try to match the word or phrase using the regular expression. Then , the object is replaced with the highlighted css, if the search matches.

First, the jQuery code, later the explanation…

jquery select text

function replaceText() {


    var searchword = $("#searchtxt").val();

    var custfilter = new RegExp(searchword, "ig");
    var repstr = "" + searchword + "";

    if (searchword != "") {
        $('body').each(function() {
            $(this).html($(this).html().replace(custfilter, repstr));


  1. $("body").find(".highlight").removeClass("highlight");

    This line removes the previously highlighted searched words.
  2. var custfilter = new RegExp(searchword, "ig");i” is used to ignore case and “g” is used to search pattern throughout string. Look at this Javascript regular expression link for more info. (of course, you can use more complex pattern matches).
  3. $("body").each(function( ) {...});

    I am looking for the search word throughout the ‘body’ element, hence , for each word in element, am comparing the lookup text. If you want to search for a particular content or block of content, then use the element ID, for example $(“#division”).each(function(){});

  4. $(this).html($(this).html().replace(custfilter, repstr));

    $(this) here refer to ‘body’ element, using java script’s “replace”  function we are replacing the searched word with the filtered word, with little css to highlight it!.


  border:#00CC00 dotted 1px; 


  <input type="text" id="searchtxt" />
  <input type="button" value="search" onClick="replaceText();" id="highlightButton" />
    The ACM Digital Library, a part of the ACM Portal, contains a comprehensive archive of the organization's journals, magazines, and conference proceedings. Online services include a forum called Ubiquity and Tech News digest.
    ACM requires the copyright of all submissions to be assigned to the organization as a condition of publishing the work.[2] Authors may post the documents on their own websites, but they are required to link back to the digital library's reference page for the paper. Though authors are not allowed to charge for access to copies of their work, downloading a copy from the ACM site requires a paid subscription.

Just added a text box and a button ; onclick of which search is triggered!.

Is it not really simple?, But wait….




Please subscribe if found useful  and click on above links to see more cool codes  🙂

Join the Conversation


Your email address will not be published. Required fields are marked *