Monday, November 30, 2015

To search and highlight text in a page

You can use window.find() in non-IE browsers and TextRange's findText() method in IE.

function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);
        
        while (window.find(text)) {
            document.execCommand("HiliteColor", false, "yellow");
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}

Reference:

http://stackoverflow.com/questions/5886858/full-text-search-in-html-ignoring-tags/5887719#5887719

No comments: