Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

window.getSelection() — document selection

window.getSelection() exposes the current document's Selection object for reading and changing its selection.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

window.getSelection()

window.getSelection() takes no arguments and delegates to document.getSelection(). The specification says it returns a Selection, or null if the document has no browsing context. Firefox can also return null for an iframe with display:none, even if its document has a browsing context. Check for null before using the result. A Selection is not a string; read its text with selection.toString().

No selection does not mean null: check rangeCount before getRangeAt(0) to avoid IndexSizeError. isCollapsed indicates coincident endpoints; it can mean a caret or an empty selection. A Range describes boundaries, whereas Selection represents the document's selection.

This is a browser Web API, not an ECMAScript feature. Having Node 24 does not prove support. The Selection API specification is a working draft, not a browser compatibility table.

Examples

(() => {
  const selection = window.getSelection();
  if (!selection) throw new Error("Selection unavailable");

  const paragraph = document.createElement("p");
  paragraph.textContent = "Hello selection";
  document.body.append(paragraph);

  const range = document.createRange();
  range.selectNodeContents(paragraph);
  selection.removeAllRanges();
  selection.addRange(range);

  console.log(selection.toString());
  console.log(selection.isCollapsed);

  selection.removeAllRanges();
  paragraph.remove();
})();

Result

Hello selection
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources