You are here: Reference > JavaScript > client-side > selection and ranges > objects > selectionRange

selectionRange object

Browser support:
9
Represents the currently selected part of the document.
Note: The selectionRange object is supported in Internet Explorer from version 9.
Use the window.getSelection method to retrieve a selectionRange object. A selectionRange object can contain more than one Range object. Every Range object represents a contiguous part of the selection.
In Internet Explorer, Opera, Google Chrome, Safari and Firefox before version 3, at most one Range can belong to the selectionRange object, because text selection is always a contiguous part of the DOM hierarchy.
In Firefox from version 3, multiple areas of text can be selected by holding down the CTRL key while selecting. If you need to select discrete blocks of text, use the addRange method.
The selected blocks can be retrieved with the getRangeAt method, the count of them with the rangeCount property. If only one block is selected, the anchorNode, anchorOffset, focusNode and focusOffset properties can be used to get the start and the end points of the selection. If more than one block is selected, use the getRangeAt method to retrieve Range objects that represent the selected blocks and the startContainer, startOffset, endContainer and endOffset properties of the Range objects to get the start and the end points of the blocks.
Note: the getSelection method does not return the selection if the selected content is within an input:password, input:text or textarea element. For those cases, use the selectionStart and selectionEnd properties.
Note that the selectionRange object represents the current state of the selection, not the state of the selection when the window.getSelection method was invoked. When the selection is modified, the selectionRange object is also modified.
In Internet Explorer (in all versions), the document.selection object provides similar functionality to the selectionRange object.

Syntax:

Methods that return the object:
window.getSelection ( )
document.getSelection ( )
The base interface, through which you can add new functionalities to the selectionRange is the Selection interface.

Possible members:

Properties:
anchorNode
Returns a reference to the node where the selection begins.
anchorOffset
Returns the start position of the selection relative to the anchor node.
focusNode
Returns a reference to the element where the selection ends.
focusOffset
Returns the end position of the selection relative to the focus node.
isCollapsed
Returns a Boolean value that indicates whether the anchor and focus points of the current selectionRange object are in the same position.
rangeCount
Returns the number of Range objects that belong to the current selection.
Methods:
addRange
Adds a Range object to the current selection.
collapse
Moves the anchor and focus points of the current selectionRange object to the same, specified point.
collapseToEnd
Moves the start point of the current selectionRange object to its end point.
collapseToStart
Moves the end point of the current selectionRange object to its start point.
containsNode
Returns whether the specified node is a part of the current selectionRange object.
deleteFromDocument
Removes the contents of the current selection from the document.
extend
Moves the focus point of the current selectionRange object to the specified point.
getRangeAt
Retrieves a Range object by position that belongs the current selectionRange object.
removeAllRanges
Cancels the current selection.
removeRange
Removes a Range object from the current selection.
selectAllChildren
Cancels the current selection and selects the child elements of the specified element.
selectionLanguageChange
Modifies the cursor Bidi level.
toString
Returns the text content of a Range or selectionRange object.

Example HTML code 1:

This example implements a cross-browser solution for displaying the selected content of the document:
<head>
    <script type="text/javascript">
        function GetSelectedText () {
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selRange = window.getSelection ();
                alert (selRange.toString ());
            }
            else {
                if (document.selection) {        // Internet Explorer
                    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

Example HTML code 2:

This example illustrates the use of the selectionRange object for multiple selections. It can store and select multiple areas of text in Firefox. Google Chrome, Safari, Opera and Internet Explorer only support simple text selection. This example does not work in Internet Explorer before version 9. For a cross-browser solution, see the next example.
<head>
    <script type="text/javascript">
        var storedSelections = [];

        function StoreSelection () {
            if (window.getSelection) {
                var currSelection = window.getSelection ();
                for (var i = 0; i < currSelection.rangeCount; i++) {
                    storedSelections.push (currSelection.getRangeAt (i));
                }
                currSelection.removeAllRanges ();
            } else {
                alert ("Your browser does not support this example!");
            }
        }

        function ClearStoredSelections () {
            storedSelections.splice (0, storedSelections.length);
        }

        function ShowStoredSelections () {
            if (window.getSelection) {
                var currSelection = window.getSelection ();
                currSelection.removeAllRanges ();
                for (var i = 0; i < storedSelections.length; i++) {
                    currSelection.addRange (storedSelections[i]);
                }
            } else {
                alert ("Your browser does not support this example!");
            }
        }
    </script>
</head>
<body>
    Select some content on this page and use the buttons below.<br /><br />
    <button onclick="StoreSelection ();">Store the selection</button>
    <button onclick="ClearStoredSelections ();">Clear stored selections</button>
    <button onclick="ShowStoredSelections ();">Show stored selections</button>
    <br /><br />
    <div>Some text for selection</div>
    <div><b>Some bold text for selection.</b></div>
</body>
Did you find this example helpful? yes no

Example HTML code 3:

This example shows how to store and restore the selection in all commonly used browsers:
<head>
    <script type="text/javascript">
        var storedSelections = [];
        var rangeObj;

        function SaveSelection (idx) {
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selection = window.getSelection ();
                if (selection.rangeCount > 0) {
                    storedSelections[idx] = selection.getRangeAt (0);
                }
            }
            else {
                if (document.selection) {   // Internet Explorer
                    var range = document.selection.createRange ();
                    storedSelections[idx] = range.getBookmark ();
                }
            }
        }


        function RestoreSelection (idx) {
            if (window.getSelection) {  // all browsers, except IE before version 9
                window.getSelection ().removeAllRanges ();
                window.getSelection ().addRange (storedSelections[idx]);
            }
            else {
                if (document.body.createTextRange) {    // Internet Explorer
                    rangeObj = document.body.createTextRange ();
                    rangeObj.moveToBookmark (storedSelections[idx]);
                    rangeObj.select ();
                }
            }
        }
    </script>
</head>
<body>
    Select any text on this page and then click here:
    <button onclick="SaveSelection (0)">Save bookmark 1!</button>
    <br /><br />
    Now, select another text on this page and then click here: 
    <button onclick="SaveSelection (1)">Save bookmark 2!</button>
    <br /><br />
    With the following buttons, the saved selections can be restored:
    <br />
    <button onclick="RestoreSelection (0)">Restore bookmark 1!</button>
    <button onclick="RestoreSelection (1)">Restore bookmark 2!</button>
</body>
Did you find this example helpful? yes no

Related pages:

External links:

User Contributed Comments

Post Content

Post Content