Search code examples
javascriptsearchfindhighlighttextrange

javascript - multiple CreateTextRange simultaniously


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;
} 

Solution

  • function findString (str) { 
        var TRange = document.body.createTextRange();
    
        while (TRange.findText(str)){
            TRange.execCommand("foreColor", false, "#ff0000");
            TRange.collapse(false);
        }
    }