views:

811

answers:

1

Does anyone know how to set the browser selection to a newly / independently created range? I understand how to get the text selection from the browser, and I understand how to create a range, but I don't know how to tell the browser to change the selection to the range I've created. I would have thought it would be something like "setSelection".

To be clear, I'm not trying to cause the selection of a textarea - I'm talking about p / div / ul tags etc.

I was referencing the following site (maybe it'll give you an idea?):

http://www.quirksmode.org/dom/range%5Fintro.html

Thanks in advance for your time.

+1  A: 

Assuming that you have a range that is a DOM Range in non-IE browsers and a TextRange in IE:

function selectRange(range) {
    var sel;

    if (window.getSelection) {
        // Non-IE browsers
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.selection && range.select) {
        // IE
        range.select();
    }
}
Tim Down