1

How can I get the selected text (in a contenteditable div) in Firefox ? It would be enough for recent versions, no need to cover old versions.

Say I have a contenteditable div that looks like the below and someone selects a text there and then hits a button, how can I copy the selected text to the clipboard or a variable ?

Example:

<div class='editInput' id='editInput'>Some awesome text</div>

My current function (working in IE):

function GetSelection() 
{
    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());
            return container.innerHTML;
        }
    }
    else if (typeof document.selection != 'undefined') 
        if (document.selection.type == 'Text') 
            return document.selection.createRange().htmlText;

    return '';
}
halfer
  • 19,824
  • 17
  • 99
  • 186
user2571510
  • 11,167
  • 39
  • 92
  • 138

2 Answers2

3
var selectedText = "" + window.getSelection();
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Hi Tim, thanks for the quick reply. Can you tell me how I would need to update the above function so that it covers this as well ? I would like to make it work in different browsers and this already works for IE. I will update the post. – user2571510 Dec 13 '13 at 09:41
  • 1
    window.getSelection() is standardized and works across browsers, don't use document.getSelection() as this incorrectly returns a string before FF 8 – WaiKit Kung Dec 14 '13 at 13:44
  • @WaiKitKung: That's true but I don't think anyone's mentioned `document.getSelection()`. – Tim Down Dec 16 '13 at 10:58
1

The other suggestions didn't work for me, but the following did:

var textArea = document.getElementById('input_text_area');
var selectedText = textArea.value.substring(textArea.selectionStart,textArea.selectionEnd);

This other answer links to some background on why the above is necessary and why window.getSelection() doesn't work on Firefox, for example.