Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Selection.getRangeAt — retrieving a selection range

Selection.getRangeAt(0) returns the Range object associated with the document selection, not a copy.

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

selection.getRangeAt(index)

selection.getRangeAt(index) exposes the selection's range. It is a browser Web API, not an ECMAScript feature; Node 24 does not establish support.

Before calling with index 0, check selection !== null and selection.rangeCount > 0. The specification requires IndexSizeError if the index is not 0, the selection is empty, or either endpoint is outside the document tree. Browsers do not always follow this rule: Firefox can expose multiple selection ranges, so a nonzero index can succeed. When an endpoint is in a shadow tree, do not assume the browser will throw this exception. A selection collapsed to a caret can still have a range.

The result is a reference: modifying the range affects the selection while they remain associated. Repeated calls with the same index return the same object unless the range is replaced or removed. The specification is a Working Draft, not a browser compatibility table.

Examples

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

  const element = document.createElement("p");
  element.textContent = "Hello world";
  document.body.append(element);

  try {
    selection.removeAllRanges();
    const range = document.createRange();
    range.setStart(element.firstChild, 0);
    range.setEnd(element.firstChild, 5);
    selection.addRange(range);

    if (selection.rangeCount === 0) {
      throw new Error("No selection range is available.");
    }
    const selectedRange = selection.getRangeAt(0);
    console.log(selectedRange.toString());
    console.log(selectedRange === selection.getRangeAt(0));
  } finally {
    selection.removeAllRanges();
    element.remove();
  }
})();

Result

Hello
true

The code and output were verified in isolated Chromium. The example retrieves the only range at index `0` and checks that a second call returns the same object. It does not test nonzero indexes or endpoints in a shadow tree.

Sources