Skip to content

Instantly share code, notes, and snippets.

@js1972
Created September 5, 2013 06:55
Show Gist options
  • Save js1972/6446805 to your computer and use it in GitHub Desktop.
Save js1972/6446805 to your computer and use it in GitHub Desktop.
#JavaScript to find and highlight text on a page (or in any element)
#all_text span
{
text-decoration:underline;
background-color:yellow;
}
<input type="text" id="searchfor"/>
<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.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</p>
$('#searchfor').keyup(function(){
var page = $('#all_text');
var pageText = page.text().replace("<span>","").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("("+searchedText+")", "igm");
var newHtml = pageText.replace(theRegEx ,"<span>$1</span>");
page.html(newHtml);
});
@js1972
Copy link
Author

js1972 commented Sep 5, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment