Range object
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
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).
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.
When an instance of a Range object exists, you can modify its boundary points the following ways:
-
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.
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 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 Range and TextRange objects.
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.
- If you need the bounding rectangle of a TextRange object, use the boundingLeft, boundingTop, boundingWidth and boundingHeight properties.
- If you need the exact shape of a TextRange object, use the getClientRects method. It retrieves a TextRectangles collection that contains TextRectangle objects. Every TextRectangle object represents a line of text that belongs to the TextRange object.
- 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.
-
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.
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.
Syntax:
Methods that return the object:
+ | object.createRange ( ) |
| 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.
|
||||||||||||||||||||||||||||||||||||
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.
|
Properties:
Returns a Boolean value that indicates whether the start and end points of the current Range are in the same position. | |||||||
Returns a reference to the deepest node in the DOM hierarchy that contains the entire Range object. | |||||||
Returns a reference to the deepest node in the DOM hierarchy that contains the end point of the current Range object. | |||||||
Returns an integer that specifies the end position of the current Range relative to the endContainer element. | |||||||
Returns a reference to the deepest node in the DOM hierarchy that contains the start point of the current Range object. | |||||||
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 |
|
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 |
|
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?
|
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?
|
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?
|
Related pages:
External links:
User Contributed Comments