0

I have the below javascript function, which when passed a word such as "Department" will highlight in red the first instance of "Department" found on the screen. However, i would like this code to highlight ALL instances of the given word.

function findString (str) { 
    var TRange=null;
    var strFound; 
    var TRange = self.document.body.createTextRange();
    TRange.findText(str);
    TRange.execCommand('foreColor', false, "#ff0000");
    return;
} 
Adam
  • 215
  • 2
  • 7
  • 14

4 Answers4

1
function findString (str) { 
    var TRange=null;
    var strFound; 
    var TRange = self.document.body.createTextRange();

    while(TRange.findText(str))
    {
        TRange.execCommand('foreColor', false, "#ff0000");
    }

    return; 
    } 
gunwin
  • 4,578
  • 5
  • 37
  • 59
  • While this looks promising, and i will try working with this a little bit.. this exact code just freezes my browser probably due to continuous loop? – Adam Apr 06 '11 at 21:09
1

This code seems to have done it, but it is sloppy and a little excessive. I'm sure there must be a shorter way to do it rather than almost duplicating my execCommand line twice in the same function.

var TRange=null;
function findString (str) { 

    var strFound; 
    var counter = 0;

    if (TRange==null || strFound==0) {
            TRange=self.document.body.createTextRange()  
            strFound=TRange.findText(str) 
            if (strFound) {
                TRange.execCommand('foreColor', false, "#ff0000");
            }
    } 

    TRange.collapse(false);
    while (strFound=TRange.findText(str)) {
        if (counter > 50){
            alert("Search exceeded maximum limit of 50.");
            return;
        }
        TRange.execCommand('foreColor', false, "#ff0000");
        TRange.collapse(false); 
        counter += 1;
    }

    return;
} 
Adam
  • 215
  • 2
  • 7
  • 14
1
function findString (str) { 
    var TRange = document.body.createTextRange();

    while (TRange.findText(str)){
        TRange.execCommand("foreColor", false, "#ff0000");
        TRange.collapse(false);
    }
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

Take a look at this link: http://www.nsftools.com/misc/SearchAndHighlight.htm

The script used on that page is a different approach to what you're taking but the end result is exactly what you're looking for.

NakedBrunch
  • 48,713
  • 13
  • 73
  • 98