2
Answers

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

josna jose

josna jose

9y
358
1
<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)