JavaScript / jQuery: how to get selected text in Firefox

1.4k views Asked by At

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 '';
}
2

There are 2 answers

3
Tim Down On
var selectedText = "" + window.getSelection();
0
inconveniently_nonexempt_bee On

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.