josna jose

josna jose

  • NA
  • 6
  • 1.4k

How to search a text which is displayed in the page content?

Nov 12 2015 6:59 AM
<script type="text/javascript">
function searchAndHighlight(searchTerm, selector) {
if (searchTerm) {
var selector = selector || "body"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm, "ig");
var matches = $(selector).text().match(searchTermRegEx);
if (matches) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html()
.replace(searchTermRegEx, "<span class='highlighted'>" + searchTerm + "</span>"));
if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
$(document).ready(function () {
$('#btnSearch').on("click", function () {
if (!searchAndHighlight($('#txtSearch').val())) {
alert("No results found");
}
});
});
</script>

In above code i have searched and highlighted the text. But issue is if i type 'in' it search whole page inner html and images(eg:-hidden fields,img name,"in" in <input type=="">).


How i search the text which is displayed in the page content or text displayed in web page.

Answers (2)