Searching for text on the current pageQuestion: 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
Example: This script gets a text string from the user
and then finds and highlights this string 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 |
|
Copyright © 1999-2011, JavaScripter.net.