You are here: Reference > JavaScript > client-side > selection and ranges > methods > getSelection (document)
getSelection method (document)
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.
- In Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9, use the window.getSelection method and the toString method of the selectionRange object returned by the window.getSelection method to get the text content of the selection.
- In older Internet Explorer versions, use the createRange method of the selection object and the text property of the TextRange object returned by the createRange method to get the text content of the selection.
Syntax:
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?
|
Supported by objects:
Related pages:
External links:
User Contributed Comments