Get the selected text

Read the text of the current document selection.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

get-the-selected-text.js
function getSelectedText() { return window.getSelection()?.toString() ?? ''; }

Usage

Markup

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

Script

usage.js
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.

Know the 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 above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Get the selected text from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Usage lines executed in headless Chromium against the fixture markup; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.