You are here: Reference > JavaScript > client-side > selection and ranges > methods > getSelection (document)

getSelection method (document)

Browser support:
9
Returns the selected content in the current document as a string.
Note: Internet Explorer supports the getSelection method from version 9.
The document.getSelection method works differently in Google Chrome, Safari and Internet Explorer than in Firefox and Opera. It returns a string in Firefox and Opera, and returns a selectionRange object in Google Chrome, Safari and Internet Explorer (the document.getSelection method is identical to the window.getSelection method in Google Chrome, Safari and Internet Explorer). Because of that, this method should not be used.

Syntax:

object.getSelection ( );
You can find the related objects in the Supported by objects section below.

Return value:

String that contains the text content of the current selection.

Example HTML code 1:

This example illustrates the use of the getSelection method:
<head>
    <script type="text/javascript">
        function GetSelectedText () {
            if (document.getSelection) {    // all browsers, except IE before version 9
                var sel = document.getSelection ();
                    // sel is a string in Firefox and Opera, 
                    // and a selectionRange object in Google Chrome, Safari and IE from version 9
                    // the alert method displays the result of the toString method of the passed object
                alert (sel);
            } 
            else {
                if (document.selection) {   // Internet Explorer before version 9
                    var textRange = document.selection.createRange ();
                    alert (textRange.text);
                }
            }
        }
    </script>
</head>
<body>
    <div>Please select <b>all</b> or a <i>part</i> of this text.</div>
    <br />
    <button onclick="GetSelectedText ()">Get selected text!</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content