Ever wanted to add a "Find In Page" feature to your web site? No? Well, since the browser already does it, nor did I. But, someone once asked how to do it on the JavaScript newsgroup and I foolishly decided to have a go. Even if you don't want to impliment this for real, it provides an interesting lesson in MSIE document manipulatuion.

In Netscape 4, the window object has a "find" method which triggers the built in "Find in Page" function as if the user selected it from the menu:

    window.find(textTofind);

    or

    top.frame.find(textToFind);

IE makes you work a bit harder. You need to use something called a TextRange object. An MSIE TextRange object represents a section of text within a page element and provides various methods for manipulating that text. You can create a TextRange object that represents all the text in a document with:

    var rng = document.body.createTextRange();

You can then find the first instance of a string and adjust the range to cover that text with:

    var found = rng.findText(textToFind);

You can then highlight the current range with:

 
    rng.select();

And finally, use:

    rng.scrollIntoView();

to make sure the selected area is visible.

If you want to go to the next step and do a "Find Next", you need to do more complex manipulation of the start and end points of the TextRange. Essentially, you need to move the start point to just after the word you have just found and repeat the find process described above.

The source code of this page implements an object called "FindInPage" (how original). To use this object, you must first create an object variable:

    var Searcher = new FindInPage();

"FindInPage" accepts an optional window variable so that you can use the object to search in another frame. for example:

    var Searcher = new FindInPage(self.frames[1]);

To find the first instance of some text in a page, use the "Find" method:

    Searcher.Find(textToFind);

To do a "Find Next", use the "FindNext" method:

    Searcher.FindNext();

Note that this will only work on Netscape 4 and IE 4+ (the "BrowserOK" property will be true if the current browser will work, false otherwise). Attempting to use it on any other browser will just do nothing.

To try it, enter some search text in the field below and click "Find".

Search for: