# Get the selected text

Read the text of the current document selection.

Canonical: https://1loc.dev/dom/get-the-selected-text/
Version: 1.0.0
Runtime: JavaScript · modern browsers (DOM)
Verification: Usage lines executed in headless Chromium against the fixture markup; no external services
Updated: 2026-10-28

## Implementation

```javascript
function getSelectedText() { return window.getSelection()?.toString() ?? ''; }
```

## Usage

Markup:

```html
<p id="quote">Small code. Working integrations.</p>
```

Script:

```javascript
const range = document.createRange();
range.selectNodeContents(document.querySelector('#quote'));
getSelection().removeAllRanges();
getSelection().addRange(range);
getSelectedText(); // → 'Small code. Working integrations.'
```

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- Text selected inside an input or textarea is not part of the document selection: read value.slice(selectionStart, selectionEnd) on the field.
- Some browsers return null from getSelection() in a hidden iframe; the fallback returns "".

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/get-the-selected-text.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
