Created
September 5, 2013 06:55
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#all_text span | |
{ | |
text-decoration:underline; | |
background-color:yellow; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('#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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jsfiddle: http://jsfiddle.net/x8rpY/1/