Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Selection.removeAllRanges() — clearing the selection

Selection.removeAllRanges() empties the document selection without deleting text or nodes. The method takes no arguments and returns undefined.

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.removeAllRanges()

Selection.removeAllRanges() dissociates the range from the selection. Afterwards, rangeCount is 0, and anchorNode and focusNode are null. Calling it again on an empty selection changes nothing.

It deletes neither content nor a saved Range object. Unlike collapseToStart(), it leaves no range collapsed to a caret. empty() is an alias for this method.

This is a browser Selection API interface, not an ECMAScript feature; Node 24 does not establish its availability. Check support in the target browser. The example contrasts the empty selection with unchanged text and a retained range.

Examples

(() => {
  const selection = window.getSelection();
  if (!selection || typeof selection.removeAllRanges !== "function") {
    throw new Error("Selection API unavailable");
  }

  const text = document.createTextNode("Hello");
  document.body.append(text);
  const range = document.createRange();
  range.selectNodeContents(text);

  selection.removeAllRanges();
  selection.addRange(range);
  selection.removeAllRanges();

  console.log(JSON.stringify({
    rangeCount: selection.rangeCount,
    anchorNode: selection.anchorNode,
    focusNode: selection.focusNode,
    text: text.data,
    savedRange: range.toString()
  }));
  text.remove();
})();

Result

{"rangeCount":0,"anchorNode":null,"focusNode":null,"text":"Hello","savedRange":"Hello"}

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