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.
This object contains info about the range of a text selection, regardless of which direction (left to right, or right to left) the selection has been made. Info is also stored about the caret position.
Both 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.
Range is a continuous selection of nodes. With a text node, it can be seen as the highlighted text. The following methods are used for a selection's range:
|addRange||Adds a range to the current selection.|
|removeAllRanges/empty||Removes all ranges of the selection.|
|getRangeAt||Returns a specified
|removeRange||Removes a range from a selection.|
|setBaseAndExtent||Sets the anchor (base) and focus (extent) boundary points for the selection.|
setBaseAndExtent, an anchor is the start of a selection and the focus is where the selection ends. Both ignore direction, meaning an anchor/focus could be at either the beginning or end of a selection.
In this code sample,
removeAllRanges is used to clear the selection range on a page:
Currently, Microsoft Edge doesn't support multiple or disjointed selections. A selection always has one range.
Collapsing is used to replace the current selection with an empty selection. Different methods provide different locations for the caret upon collapsing:
|collapse||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.|
The following code snippet shows
collapseToEnd being used to put the caret at the end of a selection made by the user upon pressing a button:
selection API includes methods that enable replacing, deleting, extending, and searching selections for nodes.
|containsNode||Determines if the given node is included in the selection.|
|deleteFromDocument||Deletes the selected nodes from a document.|
|extend||Moves the focus of the selection to a specified offset within the given node.|
|selectAllChildren||Replaces the current selection with all the contents of the given node.|
In the case of using the
extend method, the focus of the selection can be shifted forwards or backwards. The focus is the where the selection ends, regardless of direction.