Javascript Highlighter

Giganews Newsgroups
Subject: Javascript Highlighter
Posted by:  simonjohnbradl…@hotmail.com (Simon)
Date: 29 Jul 2003

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.createTextRange();
            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.selection.createRange();
                sr.pasteHTML( "<font style='background:red' id='highlightedText'>"
+ str + "</font>");
            }
            alert(r);
        }

</script>

<Form name="search" onSubmit="findInPage(this.string.value);">
    <Font size="3"><input name="string" type="text" size="15"
value="the"></font>
    <input type="submit" value="Find">
</form>
</HTML>

Replies