Skip to main content

selectionapi

Read, clear, and set text selection via the Selection API.

Import: @rtorcato/browser-common/selectionapi

๐Ÿ“– MDN: Selection

Browser supportโ€‹

APIChromeEdgeFirefoxSafariiOS SafariBaseline
Selectionโœ… 1+โœ… 12+โœ… 1+โœ… 1.3+โœ… 1+Widely available
Window.getSelectionโœ… 1+โœ… 12+โœ… 1+โœ… 1+โœ… 1+Widely available

โœ… supported ยท โ— partial ยท โŒ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: Selection ยท Window.getSelection

Exampleโ€‹

import {
isSelectionApiAvailable,
getSelectedText,
clearSelection,
selectElementText,
} from '@rtorcato/browser-common/selectionapi'

if (isSelectionApiAvailable()) {
const text = getSelectedText()
clearSelection()
selectElementText(document.querySelector('#code')!)
}

Exportsโ€‹

  • isSelectionApiAvailable() โ€” feature check
  • getSelection() โ€” the current Selection object, or null
  • getSelectedText() โ€” the currently selected text, or ''
  • clearSelection() โ€” clears the current selection
  • selectElementText(element) โ€” selects the text content of an element

See the API reference for full signatures.