Range object

Browser support:
9
Represents a contiguous part of the document.
Note: The Range object is supported in Internet Explorer from version 9.
The Range object supports properties and methods for several activities. With a Range object:
  • you can retrieve and modify any part of the document
  • you can get the placement and several other geometrical properties of a contiguous part of the document
  • you can get and modify the selected content of the document
The Range object is supported by Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9. In older Internet Explorer versions (and in newer ones as well), the TextRange object provides similar functionality.
These two objects are introduced together in the following paragraphs.
There are three ways to create a Range object:
  • You can create an empty Range object with the document.createRange method. The next section describes the way to modify the boundary points (the start and end points) of a Range object.
    You can create a TextRange object with the createTextRange method. The body and some other HTML elements support the createTextRange method. The boundary points of the newly created TextRange object will be aligned to the contents of the HTML element.
  • You can retrieve a Range object that represents the current selection with the getRangeAt method of the selectionRange object. The selectionRange object can contain more than one Range objects. 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 of the selectionRange object.
    In Internet Explorer, there are three different types of selection:
    • control selection - the selection contains controls
    • text selection - the selection contains text
    • empty selection - there is no selection (or the selected content is not available).
    You can get the type of the selection with the type property of the selection object. When the selection contains texts or there is no selected content, you can retrieve a TextRange object with the createRange method of the selection object. The boundary points of the returned TextRange object are aligned to the contents of the selection.
    The selection object supports another method to get the contents of the selection, the createRangeCollection method. It returns a TextRanges collection that contains TextRange objects. Every TextRange object represents a contiguous part of the selection. The createRangeCollection method is useful for multiple selection, but it is not supported by Internet Explorer for texts, so the use of the createRange method is sufficient.
  • You can clone an existing Range object with the cloneRange method. The returned object is identical to the original Range object.
    You can clone an existing TextRange object with the duplicate method. The returned object is identical to the original TextRange object.
When an instance of a Range object exists, you can modify its boundary points the following ways:
If you need the placement of a Range object:
  • A Range object is defined by its start and end points. An element and a position define a point. If the element has only text content (TextNode, CDATASection or CommentNode), the position specifies a character position within the element, else it specifies the index of a child of the element.
    The start and end points of a Range object are specified by the (startContainer, startOffset) and (endContainer, endOffset) properties. The startOffset property specifies the position inside the startContainer element where the Range starts. Similarly, the endOffset property specifies the position inside the endContainer element where the Range ends. These properties are read-only, so you can only retrieve the boundary points with this property.
    If you need the deepest node in the DOM hierarchy that contains the entire Range object, use the commonAncestorContainer property.
    In Internet Explorer, you cannot retrieve the elements and offsets that define the start and end points of a TextRange object. Instead, you can get the coordinates of the TextRange object's start point with the offsetLeft and offsetTop properties. All coordinates mentioned above are relative to the top-left corner of the browser window's client area.
    • The document.elementFromPoint method can help you retrieve the element that is located at the specified coordinates.
    • If you need the deepest element in the DOM hierarchy that contains the entire TextRange object, use the parentElement method.
  • A Range object is collapsed when its start and end points are at the same position. Use the collapsed method to check whether a Range is collapsed.
    You can check the collapsed state in many ways, for example with the text content of the TextRange object. The text property retrieves the text content of a TextRange object as a string. The TextRange object is collapsed only if the length of the value returned by the text property is zero.
  • The placement of two Range objects can be compared with the compareBoundaryPoints method. It compares the boundary points of the objects. If you want to check whether a point (an (element, position) pair, where the position specifies an index or a character position inside the element) is inside a Range, use the comparePoint or isPointInRange method.
    The placement of two TextRange objects can be compared with the compareEndPoints method. It compares the boundary points of the objects similarly to the compareBoundaryPoints method of the Range object.
    Note, although the syntax of the compareBoundaryPoints and compareEndPoints methods are similar, they behave differently in different browsers in some cases. For details, see the pages for them.
    You can check whether a TextRange contains another TextRange with the inRange method. The isEqual method checks whether two TextRange objects are identical.
Manipulating the contents of a Range object:
  • The toString method retrieves the text content of a Range object as a string.
    • If you need the contents of a Range object in a hierarchical DOM, then use the cloneContents and extractContents methods. These methods build a DocumentFragment object from the contents of the Range.
    • To remove the contents of a Range object from the document, use the deleteContents method.
    • To insert a new element into a Range object, use the insertNode method.
    The text property sets or retrieves the text content of a TextRange object as a string.
    If you need the contents in HTML format, use the htmlText property.
    To replace the contents of a TextRange object with HTML formatted text, use the pasteHTML method. You can also remove the contents with this method (call with empty string).
Selecting the contents of a Range object:
  • First call the window.getSelection method to retrieve a selectionRange object that represents the current selection. If you want to add the contents of a Range to the current selection, simply add the Range to the selectionRange object with the addRange method. If you only want the contents of a Range to be selected, call the removeAllRanges method of the selectionRange object before adding the Range.
    Simply call the select method of the TextRange object (multiple text selection is not possible).

Syntax:

Methods that return the object:
+object.createRange ( )
Related objects:
selectionRange.getRangeAt (rangeIndex)
The base interface, through which you can add new functionalities to the Range object, is the Range interface.

Possible members:

Constants:
The following constants are available in the scope of the Range object. Using the constants instead of their numeric values results in more readable code.
The following constants represent a boundary point pair that belongs to two Range objects. The compareBoundaryPoints method supports these values for the comparison type. You can use them directly through the Range interface (Range.START_TO_START) or through an instance of the Range object.
START_TO_START
0 Specifies that the two start points need to be compared.
START_TO_END
1 Specifies that the start point of a Range needs to be compared to the end point of the other Range. The compareBoundaryPoints method works differently for this value in browsers. See the page for the compareBoundaryPoints method.
END_TO_END
2 Specifies that the two end points need to be compared.
END_TO_START
3 Specifies that the end point of a Range needs to be compared to the start point of the other Range. The compareBoundaryPoints method works differently for this value in browsers. See the page for the compareBoundaryPoints method.
The following constants represent the placement of a node relative to the Range object. The compareNode method supports them for the returned values. You can use them directly through the Range interface (Range.NODE_BEFORE) or through an instance of the Range object.
NODE_BEFORE
0 The node is before the current Range object.
NODE_AFTER
1 The node is after the current Range object.
NODE_BEFORE_AND_AFTER
2 The node is surrounding the current Range object.
NODE_INSIDE
3 The node is inside the current Range object.
Properties:
collapsed
Returns a Boolean value that indicates whether the start and end points of the current Range are in the same position.
commonAncestorContainer
Returns a reference to the deepest node in the DOM hierarchy that contains the entire Range object.
endContainer
Returns a reference to the deepest node in the DOM hierarchy that contains the end point of the current Range object.
endOffset
Returns an integer that specifies the end position of the current Range relative to the endContainer element.
startContainer
Returns a reference to the deepest node in the DOM hierarchy that contains the start point of the current Range object.
startOffset
Returns an integer that specifies the start position of the current Range relative to the startContainer element.
Methods:
cloneContents
Creates a DocumentFragment object and copies the contents of the current Range object into it.
cloneRange
Returns an exact copy of the current Range object.
collapse
Moves the start point of a range to its end point or vice versa.
compareBoundaryPoints
Compares the placement of the start or end point of the current Range object with the placement of the start or end point of another Range object.
compareNode
3
Returns an integer that represents whether the specified node is before, inside, after, or surrounding the current Range object.
comparePoint
Returns an integer that represents whether the specified point is before, inside or after the current Range object.
createContextualFragment
Creates a DocumentFragment object from the specified HTML formatted text.
deleteContents
Deletes the contents of the current Range from the document tree.
detach
Releases the current Range object and allows the browser to free up resources.
extractContents
Creates a DocumentFragment object, copies the contents of the current Range object into it and removes the contents of current Range from the document tree.
insertNode
Inserts the specified node at the start of the current Range.
intersectsNode
3
Returns whether the specified node and the current Range object have an intersection.
isPointInRange
Returns whether a point is inside the current Range object or not.
selectNode
Aligns the start and end points of the current Range object to the start and end points of the specified node.
selectNodeContents
Aligns the start and end points of the current Range object to the contents of the specified element.
setEnd
Sets the end position of the current Range.
setEndAfter
Sets the end position of the current Range to the end position of the specified node.
setEndBefore
Sets the end position of the current Range to the start position of the specified node.
setStart
Sets the start position of the current Range.
setStartAfter
Sets the start position of the current Range to the end position of the specified node.
setStartBefore
Sets the start position of the current Range to the start position of the specified node.
surroundContents
Places the specified element to surround the contents of the current Range object.
toString
Returns the text content of a Range or selectionRange object.

Example HTML code 1:

This cross-browser example shows how the contents of an element can be deleted with Range objects:
<head>
    <script type="text/javascript">
        function RemoveContent () {
            var srcObj = document.getElementById ("src");

            if (document.createRange) {     // all browsers, except IE before version 9
                var rangeObj = document.createRange ();
                rangeObj.selectNodeContents (srcObj);
                rangeObj.deleteContents ();
            }
            else {      // Internet Explorer before version 9
                var rangeObj = document.body.createTextRange ();
                rangeObj.moveToElementText (srcObj);
                rangeObj.select ();
                rangeObj.execCommand ('cut');
            }
        }
    </script>
</head>
<body>
    <div id="src" style="background-color:#e0a0b0; width:300px; height:50px;">The <b>contents</b> of the <i>source</i> element.</div>
    <br /><br />
    <button onclick="RemoveContent ();">Remove the contents of the source element!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

This example illustrates the use of the Range object for 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) {  // all browsers, except IE before version 9
                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