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

TextRange object

Browser support:
10.5
Represents a contiguous part of the document.
The TextRange object provides properties and methods for several activities. With a TextRange 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 TextRange object is supported by Internet Explorer and partially by Opera.
In Firefox, Opera, Google Chrome and Safari, the Range object provides similar functionality. Internet Explorer also supports the Range object from version 9.
Since the Range object is supported in all modern browsers, use the TextRange object only if the Range object is not supported. These two objects are introduced together in the following paragraphs.
There are three ways to create a TextRange 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 (the start and end points) of the newly created TextRange object will be aligned to the contents of the HTML element.
    You can create an empty Range object with the document.createRange method. The next section describes the way to modify the boundary points of a Range 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 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.
  • You can clone an existing TextRange object with the duplicate method. The returned object is identical to the original TextRange object.
    You can clone an existing Range object with the cloneRange method. The returned object is identical to the original Range object.
When an instance of a TextRange object already exists, you can modify its boundary points the following ways:
  • If you want to align the boundary points of a TextRange object to the contents of an element that supports the createTextRange method, use the createTextRange method on the required element (see the previous section). For other elements, create a TextRange object with the body.createTextRange method and use the moveToElementText method with the required element.
    If you want to align the boundary points of a Range object to an element or to the contents of an element, use the selectNode or selectNodeContents method.
  • You can move the start or end point of a TextRange with the moveStart and moveEnd methods. If you want to align the start or end point of a TextRange to the start or end point of another TextRange, use the setEndPoint method.
    If you want to modify the start or end point of a Range separately, use the (setStart, setStartBefore, setStartAfter) and the (setEnd, setEndBefore, setEndAfter) methods.
  • With the collapse method you can move the start point to the end point or vice versa. This method can be used for both TextRange and Range objects.
  • You can expand the contents of a TextRange object with a unit (character, word, ...). Use the expand method for that.
If you need the placement of a TextRange object:
  • You can get the coordinates of the TextRange object's start point with the offsetLeft and offsetTop properties. The elements and offsets that define the start and end points of a TextRange object cannot be retrieved.
    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 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 (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.
  • A TextRange object is collapsed when its start and end points are at the same position. 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 if the length of the string returned by the text property is zero.
    Use the collapsed method to check whether a Range is collapsed.
  • The placement of two TextRange objects can be compared with the compareEndPoints method. It compares the boundary points of the objects.
    You can check whether a TextRange contains another TextRange with the inRange method. The isEqual method checks whether two TextRange objects are identical.
    The placement of two Range objects can be compared with the compareBoundaryPoints method. It compares the boundary points of the objects similarly to the compareEndPoints method of the TextRange object.
    Note, although the syntax of the compareBoundaryPoints and compareEndPoints methods are similar, they behave differently in different browsers in some cases. See the pages for these two methods for details.
    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.
Manipulating the contents of a TextRange object:
  • 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).
    The toString method retrieves the text content of a Range object as a string.
Selecting the contents of a TextRange object:
Some additional features for the TextRange objects:
  • The execCommand method allows to edit the contents of a TextRange object like in a rich-text editor. You can modify the color of the background or foreground, you can make text bold, italic, etc., you can cut, copy and paste the contents using the clipboard, and it provides several other functionalities.
  • A TextRange object can be saved as a bookmark with the getBookmark method. The bookmark and the moveToBookmark method can later be used to create a TextRange object that is identical to the saved one.

Syntax:

Methods that return the object:
selection.createRange ( )
+object.createTextRange ( )
TextRanges.item (index)

Possible members:

Properties:
boundingHeight
Returns an integer value that specifies the height of the rectangle that bounds the current TextRange object, in pixels.
boundingLeft
Returns an integer value that specifies the left coordinate of the rectangle that bounds the current TextRange object, in pixels.
boundingTop
Returns an integer value that specifies the top coordinate of the rectangle that bounds the current TextRange object, in pixels.
boundingWidth
Returns an integer value that specifies the width of the rectangle that bounds the current TextRange object, in pixels.
htmlText
Returns the HTML source that belongs to a TextRange object as a string.
offsetLeft
Returns the left position of an object relative to the left side of its offsetParent element, in pixels.
offsetTop
Returns the top position of the object relative to the top side of its offsetParent element, in pixels.
text
Sets or retrieves a string that specifies the text within a TextRange object.
Methods:
collapse
Moves the start point of a range to its end point or vice versa.
compareEndPoints
Compares the placement of the start or end point of the current TextRange object with the placement of the start or end point of another TextRange object.
duplicate
Returns an exact copy of the current TextRange object.
execCommand
Allows running commands on certain objects.
expand
Expands the contents of the TextRange from the insertion point by a character, sentence or word.
findText
Searches for a specified text in the document, relative to a TextRange object.
getBookmark
Saves the current TextRange object into a string (bookmark) that can be used for the moveToBookmark method to return to the original TextRange object.
getBoundingClientRect
Returns a TextRectangle object that specifies the bounding rectangle of the current element or TextRange object, in pixels, relative to the upper-left corner of the browser's client area.
getClientRects
Retrieves a TextRectangles collection that specifies the exact shape of the current element or TextRange object.
inRange
Returns whether the current TextRange object contains the specified TextRange object.
isEqual
Returns whether the current TextRange object is identical to the specified TextRange object.
move
Moves the end point of the current TextRange object to its start point and moves the collapsed TextRange object by the specified number of units.
moveEnd
Moves the end position of the current TextRange object by the specified number of units.
moveStart
Moves the start position of the current TextRange object by the specified number of units.
moveToBookmark
Moves the start and end points of the current TextRange object to the positions represented by the specified bookmark.
moveToElementText
Aligns the start and end points of the current TextRange object to the text content of the specified element.
moveToPoint
Moves the start and end points of the current TextRange object to the specified position.
parentElement
Returns a reference to the deepest node in the DOM hierarchy that contains the entire TextRange object.
pasteHTML
Replaces the contents of the current TextRange object with the specified HTML formatted text.
queryCommandEnabled
Returns whether the execution of the specified command can be successful, using the execCommand method.
queryCommandIndeterm
Returns whether the specified command is in an indeterminate state.
queryCommandState
Returns the current state of the specified command.
queryCommandSupported
Returns whether the specified command is supported by the current object.
queryCommandText
Returns the description of the specified command.
queryCommandValue
Returns the actual value of the specified command.
scrollIntoView
Scrolls the specified element into the visible area of the document.
select
Selects all text or controls that is included in the current TextRange or controlRange object.
setEndPoint
Aligns the start or end point of the current TextRange to the start or end point of the specified TextRange.

Example HTML code 1:

This example illustrates a cross-browser solution to get the selected content in the document:
<head>
    <script type="text/javascript">
        function TestSelection () {
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selectionRange = window.getSelection ();                                        
                alert ("The text content of the selection:\n" + selectionRange.toString ());
            } 
            else {
                if (document.selection.type == 'None') {
                    alert ("No content is selected, or the selected content is not available!");
                }
                else {
                    var textRange = document.selection.createRange ();
                    alert ("The text content of the selection:\n" + textRange.text);
                }
            }
        }
    </script>
</head>
<body>
    Select some text or <button>element</button>, or do not select anything, before you click on the button below.
    <br /><br />
    <button onclick="TestSelection ();">Test the selection!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

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

Related pages:

External links:

User Contributed Comments

Post Content

Post Content