Javascript Highlighter

Giganews Newsgroups
Subject: Javascript Highlighter
Posted by:  simonjohnbradl… (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?



        Leonardo da Vinci was one of the great masters of the High
        Renaissance, especially in painting, sculpture, architecture,
        engineering, and science.
        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++) {
                var sr = document.selection.createRange();
                sr.pasteHTML( "<font style='background:red' id='highlightedText'>"
+ str + "</font>");


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