views:

73

answers:

1

Hi I want to get the selection start and end index with respect to the parent node of the selected text. I am able to do this in IE. However in other browsers like Firefox, Opera, Safari and Chrome, I am able to access the selection and the index of the selected text. But my requirement is to get the index w.r.t the parent node and not the selected node. I am in need of a solution that supports all browsers - Firefox, Opera, Safari and Chrome

    if (window.getSelection) { 
                     alert("Other browser");     
                     sel = window.getSelection();

                        if(sel != '') {
               //alert(sel.anchorNode.parentNode.nodeName);
             //alert(sel.anchorOffset);
             //alert(sel.focusNode.parentNode.nodeName);
             //alert(sel.focusOffset);                
 }
                    }    
        else if (document.selection) {   
                        txt = document.selection.createRange().text;
                        var range_all = document.body.createTextRange();
                        if (txt!='' )
                        {
                            // Finding start position
                         range = document.selection.createRange();
                            range.collapse(true); 

                         var startParentElement =  range.parentElement();                 

                            range_all.moveToElementText(startParentElement);
                            for (var sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start ++)
                                range_all.moveStart('character', 1);
                            range = document.selection.createRange();
                            range.collapse(false); 
                            range_all = document.body.createTextRange();

                         var endParentElement =  range.parentElement();                 
                                                 range_all.moveToElementText(endParentElement);
                            for (var sel_end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; sel_end ++)
                              range_all.moveStart('character', 1);
    alert("sel_start:" + sel_start);
                        alert("sel_end:" + sel_end);
    }}
+1  A: 

QuirksMode site can help you here: http://www.quirksmode.org/dom/range_intro.html

You just need to learn how to use the range object in browsers other than IE.

Robusto
I am in need of two range objects - one for the selection and another one for the whole document. The code explained in the quirksmode site, helps in creating range for the selection alone. For the whole document, I tried to use window.document.createRange or just document.createRange. However I am getting back an empty value.
Radhika