I need to Highlight searched text when the page is loaded , the whole words that match a specific word to be highlighted .
I know I can use id of the div & accordingly highlight the field .
The issue here that I have a complex structure of div
I have found this over Google but this works over "p:"
var str = "test";
$(function(){
$('p:contains('+str+')').
each(function(){
var regex = new RegExp(str, "g");
$(this).html(
$(this).html().
replace( regex ,
"<span class='highlight'>"+str+"</span>"
)
);
});
});
I have tried to mess with this code to loop over div instead , but I couldn't reach a solution
The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:
innerHTML)Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.
When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.
mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:
DEMO
Alternatively you can see this fiddle.
Usage example:
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);
It's free, open-source developed by me on GitHub (project reference).
I have found an answer to my solution here .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With