Get the selected text
Read the text of the current document selection.
function getSelectedText() { return window.getSelection()?.toString() ?? ''; }
Usage
Markup
<p id="quote">Small code. Working integrations.</p>
Script
const range = document.createRange();
range.selectNodeContents(document.querySelector('#quote'));
getSelection().removeAllRanges();
getSelection().addRange(range);
getSelectedText(); // → 'Small code. Working integrations.'
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.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.