I really thought this would have been answered years ago, still I did not find any solution:
I want to highlight (i.e. make a colored background) all occurrences of a (sub-)string on an entire HTML page, completely client-side with JavaScript.
Just as you would use Ctrl+F to search inside Google Chrome: When entering the search term, it highlights all the substrings that match my entered term.
Personally, I would walk all elements of the DOM tree, doing some replace
of the search term with something like
<span style="background-color: yellow">MySearchTerm</span>
But I think there must be some more effective way?
My question:
How to use JavaScript (or jQuery) to highlight all substring occurrences inside a HTML page?
Highlight Text Using the Mark Tag Method in JavaScriptIf you surround any text inside the mark tag, the browser will automatically highlight it in a striking yellow color. This will make highlighting a searched text quite a simple task then.
js code to highlight the text. There are many built-in functions in mark. js but we are using two functions for our requirement that is mark() and unmark() function respectively. Here mark() is used to highlight the search text and unmark() is used to remove highlighting the text that is highlighted before.
The HTML <mark> tag is used to mark or highlight text that is of special interest or relevance in an HTML document. Browsers traditionally render the text found within the <mark> tag as text with a yellow background color. This tag is also commonly referred to as the <mark> element.
I struggled to find a robust text highlighter that duplicates the browsers ctrl + f functionality for months. I've used a host of jQuery plugins. Some are better than others but none are capable of spanning HTML. Say you want to find text that includes a link - the browser can do it but no jQuery plugins I've found can.
Turns out bare naked javascript has the answer. Just window.find()
.
find(string, matchcase, searchBackward)
string : The text string for which to search.
matchcase : Boolean value. If true, specifies a case-sensitive search. If you supply this parameter, you must also supply backward.
searchBackward : Boolean. If true, specifies a backward search. If you supply this parameter, you must also supply casesensitive.
It highlights html laden strings and it's compatible with every browser you care about. Read more about it at http://www.w3resource.com/javascript/client-object-property-method/window-find.php
The unfortunate thing is you can't seem to do anything with it. I can't wrap it in styled span tags, get the position, scroll to it or change the highlight colour. I'm still looking for the ideal ctrl + f JS function.
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