JavaScript Document getSelection() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.getSelection() is an instance method that returns the document’s Selection object — the text the user highlighted, or the caret position (see MDN Document: getSelection()). Learn how to read selected text, work with ranges, and how selection differs from focus.

01

Kind

Instance method

02

Args

None

03

Returns

Selection / null

04

Text

toString()

05

Alias

window.getSelection

06

Status

Baseline

Introduction

When a visitor highlights words on a page — or places the caret in editable text — the browser tracks that as a selection. document.getSelection() is how JavaScript reads it.

MDN: the method returns the Selection object associated with this document, representing the range of text selected by the user, or the current position of the caret.

💡
Think: “what did the user highlight?”

1) Call document.getSelection()
2) Get a Selection object (or null)
3) Read text with selection.toString()
4) Or dig into ranges with getRangeAt(0)

⚠️
Selection is not focus (MDN)

MDN reminds you that selection and focus are different. Document.activeElement returns the focused element — not the highlighted text. A button can be focused while no text is selected.

Related tutorials: getElementsByTagNameNS(), getElementById(), hasFocus().

Understanding document.getSelection()

An instance method on the Document interface (MDN). It takes no arguments and returns the current selection state for that document.

  • No parameters — call it with empty parentheses (MDN).
  • Return value — a Selection object, or null without a browsing context (MDN).
  • Selected text — use selection.toString() for a string (MDN).
  • Rangesselection.getRangeAt(0) for the first range (MDN example).
  • Window aliasWindow.getSelection() is identical to window.document.getSelection() (MDN).
  • Input caveat — MDN: currently getSelection() doesn’t work on the content of <input> elements in Firefox; HTMLInputElement.setSelectionRange() can help.

📝 Syntax

General form of Document.getSelection (MDN):

JavaScript
getSelection()

Parameters

None (MDN).

Return value

A Selection object, or null if the document has no browsing context — for example, it is the document of an <iframe> that is not attached to a document (MDN).

MDN quick sample

JavaScript
const selection = document.getSelection();
const selRange = selection.getRangeAt(0);
// do stuff with the range
console.log(selection); // Selection object

let selectedText = selection.toString();

⚡ Quick Reference

GoalCode
Get Selectionconst sel = document.getSelection()
Selected textsel.toString()
First rangesel.getRangeAt(0)
Is anything selected?sel && !sel.isCollapsed
Window formwindow.getSelection()
MDN statusBaseline Widely available (since Nov 2017)

🔍 At a Glance

Four facts about document.getSelection().

Returns
Selection

or null

Args
none

MDN

Text
toString()

explicit

Status
Baseline

since 2017

📋 Object vs string representation

Selection objectString form
How you get itdocument.getSelection()selection.toString() (MDN)
alert(selection)May auto-call toString() (MDN)Shows the selected text
Need ranges / APIsKeep the objectNot enough alone
Beginner tipLog the object to exploreCall toString() when you need text

Examples Gallery

Examples follow MDN Document: getSelection() and practical beginner patterns.

📚 Getting Started

Read the current Selection after the user highlights text.

Example 1 — Get a Selection object

MDN’s starting point: store the selection and inspect it.

JavaScript
const selection = document.getSelection();
console.log(selection); // Selection object
console.log(selection && selection.type);
Try It Yourself

How It Works

You always get the live selection for the document. Highlight different words and call again — the object reflects the new state.

Example 2 — Read selected text with toString()

MDN: call toString() explicitly when you need a string.

JavaScript
const selection = document.getSelection();
const selectedText = selection ? selection.toString() : "";
console.log(selectedText);

// alert(selection) may auto-call toString() (MDN)
// but prefer the explicit form above
Try It Yourself

How It Works

Not every function coerces the Selection to a string automatically. MDN recommends calling toString() yourself for predictable results.

📈 Practical Patterns

Ranges, empty selections, and focus comparisons.

Example 3 — First range with getRangeAt(0)

MDN example: grab the first range for deeper DOM work.

JavaScript
const selection = document.getSelection();
if (selection && selection.rangeCount > 0) {
  const selRange = selection.getRangeAt(0);
  console.log(selRange.startContainer.nodeName);
  console.log(selRange.toString());
}
Try It Yourself

How It Works

Check rangeCount before getRangeAt so you avoid errors when nothing is selected.

Example 4 — Detect an empty (collapsed) selection

A caret with no highlight is still a Selection — often collapsed.

JavaScript
const selection = document.getSelection();
if (!selection || selection.isCollapsed) {
  console.log("No text highlighted (caret only or empty)");
} else {
  console.log("Highlighted:", selection.toString());
}
Try It Yourself

How It Works

MDN: the Selection can represent a text range or the caret position. isCollapsed helps tell those cases apart.

Example 5 — Selection vs activeElement

MDN: selection and focus are different concepts.

JavaScript
const selection = document.getSelection();
const focused = document.activeElement;

console.log("selected text:", selection ? selection.toString() : "");
console.log("focused tag:", focused && focused.tagName);
Try It Yourself

How It Works

Clicking a button focuses it even when no text is highlighted. Use both APIs when your UI needs keyboard focus and text selection.

🚀 Common Use Cases

  • Copy helpers — read the highlighted string for a custom copy button.
  • Annotate / quote — capture selected text for notes or sharing.
  • Editor tools — wrap the current range in bold/italic markup.
  • Word count — measure only the highlighted portion of an article.
  • Focus-aware UI — combine with activeElement when needed (MDN).
  • Input fields in Firefox — MDN: prefer setSelectionRange for <input> selection quirks.

🧠 How getSelection() Works

1

User selects text or places the caret

The browser tracks the current selection for the document (MDN).

User
2

Call document.getSelection()

No arguments — returns the Selection for this document (MDN).

Call
3

Read text or dig into ranges

Use toString() or getRangeAt(0) (MDN).

Use
4

Build features on top

Copy, annotate, format, or compare with focus as needed.

📝 Notes

  • MDN: Baseline Widely available since November 2017.
  • MDN: may return null when the document has no browsing context.
  • MDN: Window.getSelection() is identical to window.document.getSelection().
  • MDN: call toString() explicitly when you need the selected text as a string.
  • MDN: selection ≠ focus; use activeElement for the focused element.
  • Related: getElementsByTagNameNS(), getElementById(), hasFocus().

Browser Support

Document.getSelection() is Baseline Widely available on MDN (since November 2017). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.getSelection()

Selection object for user-highlighted text and caret position across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
getSelection() Wide

Bottom line: Use getSelection to read highlighted text and caret ranges. Remember it differs from focus (activeElement), and watch input quirks in Firefox.

Conclusion

document.getSelection() returns the document’s Selection object so you can read highlighted text, inspect ranges, or react to the caret. Prefer explicit toString(), and remember selection is not the same as focus.

Continue with getElementsByTagNameNS(), hasFocus(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Call toString() when you need selected text (MDN)
  • Check rangeCount before getRangeAt
  • Handle null for documents without a browsing context (MDN)
  • Use activeElement when you care about focus (MDN)
  • Test form-field selection separately (Firefox input note on MDN)

❌ Don’t

  • Assume every API auto-stringifies a Selection (MDN)
  • Confuse selection with activeElement focus
  • Call getRangeAt(0) when rangeCount is 0
  • Expect identical <input> behavior in every browser (MDN)
  • Forget window.getSelection() is the same API (MDN)

Key Takeaways

Knowledge Unlocked

Five things to remember about getSelection()

Read the user’s text selection and caret.

5
Core concepts
🔄02

Text

toString()

MDN
🎯03

Ranges

getRangeAt

MDN
04

≠ focus

activeElement

MDN
🛡05

Status

Baseline

2017

❓ Frequently Asked Questions

MDN: Document.getSelection() returns the Selection object associated with this document, representing the range of text selected by the user, or the current position of the caret.
No. MDN marks Document.getSelection() as Baseline Widely available (since November 2017). It is not Deprecated, Experimental, or Non-standard.
A Selection object, or null if the document has no browsing context — for example, the document of an iframe that is not attached to a document (MDN).
Call selection.toString(). Some functions like alert() call toString() automatically, but not all do — MDN recommends calling toString() explicitly when you need a string.
Yes. MDN: Window.getSelection() is identical to window.document.getSelection().
No. MDN: notice the difference between selection and focus. Document.activeElement returns the focused element.
Did you know?

MDN points out that alert(selection) often shows the selected text because alert calls toString() for you — but many other APIs will not, so explicit selection.toString() is the safer habit.

Next: hasFocus()

Learn how to check whether this document currently has keyboard/UI focus.

hasFocus() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful