Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

getSelectedText

Returns the currently selected text in the document, if any.

TypeScript
Copied!
1/**
2 * Returns the currently selected text in the document, if any.
3 *
4 * @returns The selected text or an empty string.
5 */
6export function getSelectedText(): string {
7  const selection = window.getSelection();
8  return selection ? selection.toString() : '';
9}
  • Simple and Direct Access

    Provides a concise way to retrieve user-selected text without extra DOM manipulation or third-party libraries.

  • Graceful Fallback

    Safely handles cases where no text is selected, returning an empty string instead of throwing errors.

  • Cross-Browser Compatibility

    Uses the standardized window.getSelection() API supported by all modern browsers.

  • Zero Dependencies and Minimal Overhead

    Lightweight utility with no setup or teardown required, ideal for real-time interactions.

Tests | Examples

TypeScript
Copied!
1let container: HTMLDivElement;
2
3beforeEach(() => {
4  container = document.createElement('div');
5  container.innerHTML = '<p id="p1">Hello world</p>';
6  document.body.appendChild(container);
7});
8
9afterEach(() => {
10  window.getSelection()?.removeAllRanges();
11  document.body.removeChild(container);
12});
13
14test('returns selected text', () => {
15  const range = document.createRange();
16  const textNode = container.querySelector('#p1')?.firstChild!;
17  range.setStart(textNode, 0);
18  range.setEnd(textNode, 5); // "Hello"
19
20  const selection = window.getSelection();
21  selection?.removeAllRanges();
22  selection?.addRange(range);
23
24  expect(getSelectedText()).toBe('Hello');
25});
26
27test('returns empty string when nothing is selected', () => {
28  const selection = window.getSelection();
29  selection?.removeAllRanges();
30
31  expect(getSelectedText()).toBe('');
32});
33
34test('returns empty string when getSelection is null', () => {
35  const original = window.getSelection;
36  // @ts-expect-error simulate null selection
37  window.getSelection = () => null;
38
39  expect(getSelectedText()).toBe('');
40
41  window.getSelection = original; // restore
42});

Common Use Cases

  • Copy-to-Clipboard Tools

    Capture highlighted text to enhance copy or share functionality.

  • Custom Context Menus

    Trigger context-specific options (e.g., "Search", "Highlight") based on selected text.

  • Text Annotation or Commenting Systems

    Identify selected ranges for user-driven markup or discussion threads.

  • Accessibility Enhancements

    Provide real-time feedback, audio playback, or magnification of selected text for assistive purposes.

Codebase: Utilities -> Browser & DOM -> getSelectedText | Yevhen Klymentiev