Click to return to the DHTML, HTML     
Using the TextRange Objec...     Positioning     Dynamic Content    
Web Workshop  |  DHTML, HTML & CSS

Finding Text in the Document


You can search for a given string of text in a document by using the findText method on a TextRange object. This method starts the search at the beginning of the range and, if it finds the string, positions the range so that it entirely encloses the string. The following example uses findText to search for each instance of the word "sample" and displays a message identifying how many instances it found.

var rng = document.body.createTextRange();
for (i=0; rng.findText("sample")!=false; i++) {
    rng.collapse();
}
alert("There are " + i + " instances of sample");

This feature requires Internet Explorer 4.0 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

In the above example, the collapse method moves the start of the text range to the same position as the end point, ensuring that the same instance of "sample" is not counted twice.

You can carry out a global search and replace by using findText and the text property. The following example searches for each instance of "sample" and replaces it with the word "final".

var rng = document.body.createTextRange();
for (i=0; rng.findText("sample")!=false; i++) {
    rng.text = "final";
}

This feature requires Internet Explorer 4.0 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

You can select the text that you find, making it easier for the user to see, by using the select method. Similarly, you can scroll the text into the user's view by using the scrollIntoView method. Together, these methods give you a way to make the result of a search clearly visible to the user. The following JScript (compatible with ECMA 262 language specification) example searches for the word "sample", selects the word, and then scrolls the word to the top of the window.

var rng = document.body.createTextRange();
if (rng.findText("sample")==true) {
    rng.select();
    rng.scrollIntoView();
}

This feature requires Internet Explorer 4.0 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Note that you can also create a text range from a selection made by the user. The createRange method on the selection object returns a text range. You can use the same methods and properties on this range as you do for ranges created using createTextRange.



Back to topBack to top

Did you find this topic useful? Suggestions for other topics? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.