You can see the Google search results and many other sites that have good search functionality. When you perform a search, your words or phrases are highlighted in the search results making it easy to find out the most relevant content.
Here the highlight search text function has an optional parameter which is determine whether the individual words in a search term should be highlighted separately, or if they should be treated as a phrase. By default, texts will be split and highlighted individually.
Some notes about using these functions:
- you can call onload event of the body tag functions from a button or link or something that’s triggered after the page is loaded.
- The performance may slow if large number of matches on a big web page.
- If there are HTML tags between letters of a word or between words in a phrase, then the word/phrase will not be highlighted as a match. For example, a search for “plant” will not match the word Sujit, because the HTML representation of the word is “s<u>uji</u>t”, and the HTML tags will throw the search off. Likewise, if you highlight part of a word using a search, and then try to highlight the word itself, the word will not be matched for the same reason (if you search for and highlight “it” and then try to search for and highlight “sujit”, you won’t get any matches for “sujit” because the HTML for the word will have been changed to “su<highlightStartTag>jit<highlightEndTag>”).
- I tested this code with IE6, IE7, IE8, mozilla Firefox, Google chrome, safari and it worked. Now I suppose the code is cross-browser compatible.