Search code examples
jqueryhtmlcsssearchhighlight

JQuery search in static HTML page with highlighting of found word


I've been trying to make a simple search inside a static HTML page using JQuery. I have to mention that this is just my first time working with JQuery.

I'm trying to change the background of the found word in the page and this is what I've tried so far:

myJavascript.js:

$(document).ready(function(){

     $('#searchfor').keyup(function(){
         page = $('#all_text').text();
         searchedText = $('#searchfor').val();
         $("p:contains('"+searchedText+"')").css("color", "white");
    });
});

Here's the HTML code as well:

page.html:

<html>
<head>
    <title>Test page</title>
</head>
<body bgcolor="#55c066">
<input type="text" id="searchfor"></input>
    <p id="all_text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
    <font color="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</font>
    </p>
</body>
    <script src="jquery-1.7.2.min.js"></script>
    <script src="myJavascript.js"></script>
</html>

After inspecting the page with Firebug I can see that the variables in JQuery do get the value from the input field but I guess I'm messing up the highlighting part.

Thanks in advance for your help!


Solution

  • Do something like this

     $("p:contains('"+searchedText+"')").each( function( i, element ) {
          var content = $(element).text();
          content = content.replace( searchedText, '<span class="search-found">' + searchedText + '</span>' );
          element.html( content );
     });
    
     .search-found {
         text-decoration: underline;
     }
    

    p.s. this will work only if each of the "elements" has plain text only content otherwise it would remove children nodes

    EDIT: removed the extra ')' in the each callback