https://github.com/nikku/selection-ranges
Manipulate selection ranges on contenteditable elements.
https://github.com/nikku/selection-ranges
Last synced: over 1 year ago
JSON representation
Manipulate selection ranges on contenteditable elements.
- Host: GitHub
- URL: https://github.com/nikku/selection-ranges
- Owner: nikku
- License: mit
- Created: 2018-02-17T21:30:18.000Z (over 8 years ago)
- Default Branch: main
- Last Pushed: 2025-01-18T16:42:52.000Z (over 1 year ago)
- Last Synced: 2025-04-03T01:09:36.952Z (over 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 450 KB
- Stars: 20
- Watchers: 2
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# selection-ranges
[](https://github.com/nikku/selection-ranges/actions/workflows/CI.yml)
Manipulate selection ranges on `contenteditable` elements.
## API
```javascript
/**
* Return the selection on the given element as {start, end}.
*
* @param {Element} el
*
* @return {Object} selection range or null if element is not selected
*/
getRange(el);
```
```javascript
/**
* Selects the given range on the specified element.
*
* @param {Element} el
* @param {Object} range {start, end}
*/
setRange(el, range);
```
```javascript
/**
* Return true if element is part of window selection.
*
* @param {Element} el
* @return {Boolean}
*/
isSelected(el);
```
## Usage
```javascript
import {
getRange,
setRange
} from 'selection-ranges';
var node =
;
let range = getRange(node);
// a range such as { start: 5, end: 10 }
// or null if node is currently not selected
setRange(node, { start: 0, end: 30 });
// sets selection range to child nodes; does not focus node
```
## Features
* Works around [browser issues](https://stackoverflow.com/questions/13949059/persisting-the-changes-of-range-objects-after-selection-in-html/13950376) and correctly handles `
` and paragraph elements
* Correctly handles out-of-bounds selections
## Related
* [selection-update](https://github.com/nikku/selection-update) - compute input selection updates on external content changes
## License
MIT