Selection composed ranges
The Selection.getComposedRanges() method returns an array of StaticRange objects representing the current selection ranges, and can return ranges that potentially cross shadow boundaries.
As the selection range endpoints may be within a shadow tree, or even different shadow trees, and because these may be closed, the method cannot by default return nodes from within a shadow tree. If the method needs to return a selection that includes nodes inside shadow trees, then the ShadowRoot objects for these trees must be passed as arguments to the method. If a corresponding roots are not provided and the start or endpoint of the selection are within a shadow tree, the returned range is re-scoped to include the host of the shadow root rather than some node with in the root.
The returned ranges represent the range at the time that getComposedRanges() was called. If the DOM or a shadow DOM is mutated, the selected range is likely to be incorrect. Application code might use a MutationObserver to monitor for DOM mutations and then call Selection.setBaseAndExtent() to update the selection.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 137 | 137 | 142 | 17 | 137 | 17 | |
Syntax
getComposedRanges()
getComposedRanges(options) Use cases
-
Using Selection composed ranges
The Selection.
Cautions
- May not be supported in older browsers.
Implementation notes
- Some APIs require a secure context (HTTPS) or user activation. Check the requirements before use.