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

TextRanges collection

Browser support:
Represents a collection of TextRange objects that belong to the current selection.
You can get an instance of the TextRanges collection with the createRangeCollection method. The return value of the createRangeCollection method depends on the type of the current selection. You can get the type of the selection with the type property of the selection object. When the value of the type property is 'Control', the createRangeCollection method returns a controlRange collection, else it returns a TextRanges collection.
Every TextRange object in the TextRanges collection represents a contiguous part of the selection. Multiple selection is not supported for text content in Internet Explorer, so the TextRanges collection returned by the createRangeCollection method always contains exactly one TextRange object.
Use the selectionRange object to get similar funcionality in Firefox, Opera, Google Chrome and Safari (and in Internet Explorer from version 9).

Syntax:

Methods that return the object:
selection.createRangeCollection ( )

Possible members:

Properties:
length
Returns an integer that specifies the number of objects in the current collection.

This property is read-only.
Methods:
[index]
Returns an object from the current collection by index.

Parameters:

index
Required. Zero-based integer that specifies the position of object to retrieve.

Return value:

Returns a TextRange object.
item (index)
Returns an object from the current collection by index.

Parameters:

index
Required. Zero-based integer that specifies the position of object to retrieve.

Return value:

Returns a TextRange object.

Example HTML code 1:

This example illustrates the use of the TextRanges collection:
<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.createRangeCollection) { // Internet Explorer
                    var textRanges = document.selection.createRangeCollection ();
                    var textRange = textRanges[0];
                    alert (textRange.text);
                }
            }
        }
    </script>
</head>
<body>
    Select some text!
    <button onclick="GetSelectedText ()">Get the selected text!</button>
</body>
Did you find this example helpful? yes no

External links:

User Contributed Comments

Post Content

Post Content