JavaScript / jQuery: get selection function not working in Firefox and Chrome

2.5k views Asked by At

I am using the following function to get the selected text (i.e. text selected by the user) in a contenteditable div. This works perfect in IE 9 but not in IE 8, Firefox or Chrome (both latest versions).

Can someone here help me to modify this in a way that it works at least in Firefox and IE 8 as well (Chrome is not a must) ?

My function (working):

function GetSelection() 
{
selTxt = '';

if (typeof window.getSelection != "undefined") 
{
    var sel = window.getSelection();
    if (sel.rangeCount) 
    {
        var container = document.createElement('div');
        for (var i = 0, len = sel.rangeCount; i < len; ++i) 
        {
            container.appendChild(sel.getRangeAt(i).cloneContents());
        }
        selTxt = container.innerHTML;
    }
} 
else if (typeof document.selection != 'undefined') 
{
    if (document.selection.type == 'Text') 
    {
        selTxt = document.selection.createRange().htmlText;
    }
}
return selTxt;
}

Many thanks for any help with this, Tim.

1

There are 1 answers

1
uyitalk On BEST ANSWER
    function myGetSelection(){
         if(document.selection){ //IE
                return document.selection.createRange().text;
          } else{
                return window.getSelection().toString();
          }
   }