Highlighting Selected Words
Introduction and Sample
Join the Discussion
More of this Feature
You have probably seen web pages where the keywords that you searched on in order to find the page are then highlighted in the page so that you can see where all of the occurrences of the words you were looking for are to be found in that page. There are a number of ways to achieve that effect so here we're going to look at the simplest way to do it by adding a small piece of Javascript to the page itself.
Let's start by looking at how the effect will work. The following links will highlight all occurrences of the words listed where ever they occur on this page using bold red text on a yellow background.
So how can we create this effect? Well the "correct" way to do it would be to traverse the DOM structure of the page updating each text node that contains a word to be highlighted by splitting that node into three and applying the highlighting to the appropriate nodes. That would involve a huge amount of code. A much simpler method is to grab the entire content of the body of the web page using an innerHTML call and then use regular expressions to stick all of the words to be highlighted inside span tags everywhere that those words occur. We just have to make sure that we only apply the span tags around text and don't insert them inside of the existing HTML tags in our page or between textarea or script tags (style tags would also be a problem but then they aren't allowed in the body of the page).
To determine what words we want to highlight we'll pass a query string on the end of the address of the page specifying hilite= followed by a comma separated list of the words to be hightlighted. Also because we are just adding span tags around the text to be highlighted you can easily change the actual way that the highlighted text is to look just by changing the stylesheet entry for the hl class that we are adding in the span tag.
To add the ability to highlight selected words in your web pages the first step is to get the script.

