Searching for text on the current page

JavaScript FAQ | JavaScript Dialogs FAQ  

Question: How do I search for a particular text string on the page?

Answer: In several browsers (e.g. Netscape, Firefox, Safari, Google Chrome), to search for a string programmatically, you can use the

window.find(string)
method; see also Find Dialog. Internet Explorer does not support this method. However, in Internet Explorer 4 and newer, you can create a text range object (
TRange
in the example below) and use the method
TRange.findText(string)
.

Example: This script gets a text string from the user and then finds and highlights this string on the page.


Here is the JavaScript source code of the
findString
function used in this example:
var TRange=null;

function findString (str) {
 if (parseInt(navigator.appVersion)<4) return;
 var strFound;
 if (window.find) {

  // CODE FOR BROWSERS THAT SUPPORT window.find

  strFound=self.find(str);
  if (!strFound) {
   strFound=self.find(str,0,1);
   while (self.find(str,0,1)) continue;
  }
 }
 else if (navigator.appName.indexOf("Microsoft")!=-1) {

  // EXPLORER-SPECIFIC CODE

  if (TRange!=null) {
   TRange.collapse(false);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
  if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange();
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
 }
 else if (navigator.appName=="Opera") {
  alert ("Opera browsers not supported, sorry...")
  return;
 }
 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}

Note that in some browsers (e.g. Firefox 2.0 and newer) the

window.find()
method may find and highlight not only the existing text on the page but also the user's input text in forms, including the search box itself. To avoid this incompatibility, in the above example we have not included the
<input>
tag defining the search box in the HTML code of the current page; instead, we load the search box via an
IFRAME
element. The content in any
FRAME
or
IFRAME
is not directly accessible via the current
window
object, and therefore cannot be found with
window.find()
.

Copyright © 1996-2018, JavascriptFAQ.net.