Newbie question:
How can I use a TextRange object to search for text, and then
highlight it?
The enclosed example works, until you dismiss the alert (done just to
show the results). I would rather the text stayed selected! I guess it
is because the TextRange object r goes out of scope? or summat?
Any ideas?
Cheers,
Simon
<HTML>
<BODY>
Leonardo da Vinci was one of the great masters of the High
Renaissance, especially in painting, sculpture, architecture,
engineering, and science.
</BODY>
<SCRIPT>
var r;
function findInPage(str) {
r = document.body.c reateTextRange( );
var txt = r.text;
var matches = txt.toString(). match(new RegExp(str, "g"));
matches = matches ? matches.length : 0;
for (i = 0; i <= matches -1; i++) {
r.findText(str) ;
r.select();
var sr = document.select ion.createRange ();
sr.pasteHTML( "<font style='backgrou nd:red' id='highlighted Text'>"
+ str + "</font>");
}
alert(r);
}
</script>
<Form name="search" onSubmit="findI nPage(this.stri ng.value);">
<Font size="3"><input name="string" type="text" size="15"
value="the"></font>
<input type="submit" value="Find">
</form>
</HTML>
How can I use a TextRange object to search for text, and then
highlight it?
The enclosed example works, until you dismiss the alert (done just to
show the results). I would rather the text stayed selected! I guess it
is because the TextRange object r goes out of scope? or summat?
Any ideas?
Cheers,
Simon
<HTML>
<BODY>
Leonardo da Vinci was one of the great masters of the High
Renaissance, especially in painting, sculpture, architecture,
engineering, and science.
</BODY>
<SCRIPT>
var r;
function findInPage(str) {
r = document.body.c reateTextRange( );
var txt = r.text;
var matches = txt.toString(). match(new RegExp(str, "g"));
matches = matches ? matches.length : 0;
for (i = 0; i <= matches -1; i++) {
r.findText(str) ;
r.select();
var sr = document.select ion.createRange ();
sr.pasteHTML( "<font style='backgrou nd:red' id='highlighted Text'>"
+ str + "</font>");
}
alert(r);
}
</script>
<Form name="search" onSubmit="findI nPage(this.stri ng.value);">
<Font size="3"><input name="string" type="text" size="15"
value="the"></font>
<input type="submit" value="Find">
</form>
</HTML>
Comment