Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Selection — document selection

Selection represents document selection. Learn rangeCount and how to attach a range using addRange.

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

const selection = window.getSelection();
selection.rangeCount;
selection.removeAllRanges();
selection.addRange(range);

Selection represents document selection; Range defines its boundaries. Obtain it through window.getSelection() and check for null. This is a Web API, not an ECMAScript feature; Node 24 does not establish browser support.

Selection.rangeCount is read-only: the specification requires 0 if the selection is empty or its boundaries are outside the document tree, and 1 otherwise. A collapsed range can still yield 1 — this does not imply selected text.

When Selection.addRange(range) adds a range, it retains a reference, not a copy. The specification says the method does nothing if the range is outside the document tree or if Selection.rangeCount is nonzero. Firefox, however, allows multiple ranges to be added, so Selection.rangeCount can exceed 1 there. Do not rely on multiple-range support across browsers. To replace the selection, call removeAllRanges() before adding the new range.

Examples

(() => {
  const selection = window.getSelection();
  if (!selection || !document.body) {
    throw new Error('An active browser document with a body is required.');
  }

  const paragraph = document.createElement('p');
  paragraph.textContent = 'Hello Selection';
  document.body.append(paragraph);

  const range = document.createRange();
  range.setStart(paragraph.firstChild, 6);
  range.setEnd(paragraph.firstChild, 15);

  try {
    selection.removeAllRanges();
    selection.addRange(range);
    console.log(selection.rangeCount + ': ' + selection.toString());

    range.collapse(true);
    console.log(selection.rangeCount + ': ' + selection.isCollapsed);
  } finally {
    selection.removeAllRanges();
    paragraph.remove();
  }
})();

Result

1: Selection
1: true

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