Selection object
Represents the active selection, which is typically a highlighted block of text or other elements in the document. The active selection can be used to complete an action issued by a user or a script.
![]() ![]() |
Members
The Selection object has these types of members:
Methods
The Selection object has these methods.
| Method | Description |
|---|---|
| addRange |
Adds a Range to the current selection. |
| collapse (setPosition) |
Replaces the current selection with an empty selection (or a caret) at the given offset. |
| collapseToEnd |
Collapses or sets the insertion point or caret at the end of a selection object. |
| collapseToStart |
Collapses, or sets the insertion point or caret at the beginning of a selection object. |
| containsNode |
Determines if the given node is included in the selection. |
| deleteFromDocument |
Deletes the selected nodes from a document. |
| empty |
Removes all ranges of the selection. |
| extend |
Moves the focus of the selection to a specified offset within the given node. |
| getRangeAt |
Returns a specified Range from a selection. The Range is specified by an index and cannot be greater than the number that is returned by rangeCount. |
| removeAllRanges |
Removes all ranges from a selection. |
| removeRange |
Removes a range from a selection. |
| selectAllChildren |
Replaces the current selection with all the contents of the given node. |
| setBaseAndExtent |
Sets the anchor (base) and focus (extent) boundary points for the selection. |
Properties
The Selection object has these properties.
| Property | Description |
|---|---|
|
Returns the element or node that contains the start of the selection. | |
|
Retrieves the starting position of a selection that is relative to the anchorNode / baseNode. | |
|
Retrieves the element or node that contains the end of a selection. | |
|
Retrieves the end position of a selection that is relative to the focusNode / extentNode. | |
|
Retrieves whether a selection is collapsed or empty. | |
|
Returns the number of ranges in a selection |
Standards information
- HTML5 A vocabulary and associated APIs for HTML and XHTML, Section 7.6.1
Remarks
You can use the Selection object as input from the user to identify which portion of the document to act on, or as output to the user to show the results of an action.
Users and scripts can create selections. Users create selections by dragging a finger or mouse over a portion of the document. Scripts create selections by calls to selection methods. To get the active selection, apply the getSelection method to the document object.
A document can have only one selection at a time. Use the isCollapsed property to test whether a selection is empty. Although an empty selection contains nothing, you can use it to mark a position, or place a caret in the document.

