This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

DOM Range API Cheat Sheet

A quick reference guide for the browser DOM Range API (document.createRange): endpoints, boundary offsets, selection, node insertion, and extraction.

· Published

A quick reference guide to the standard browser DOM Range API (document.createRange()).

🔗 Related: DOM Selection API Cheat Sheet

Creating a Range

const range = document.createRange();

Setting Boundaries

// Set start and end by node container and character/child index offset
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);

// Set relative to surrounding elements
range.setStartBefore(node);
range.setStartAfter(node);
range.setEndBefore(node);
range.setEndAfter(node);

// Quick selection over an entire node or its inner contents
range.selectNode(node);          // Includes node itself
range.selectNodeContents(node);  // Selects all child nodes within node

Collapsing Boundaries

range.collapse(true);  // Collapse range to start point (caret at beginning)
range.collapse(false); // Collapse range to end point (caret at end)
console.log(range.collapsed); // true if start and end points are identical

Content Manipulation

// Copy: returns a DocumentFragment without modifying the DOM
const fragment = range.cloneContents();

// Cut: removes selected contents from DOM and returns DocumentFragment
const extracted = range.extractContents();

// Delete: removes contents from DOM entirely
range.deleteContents();

// Insert an element at the range start position
range.insertNode(newNode);

// Surround range contents with an element
range.surroundContents(document.createElement('mark'));

Read-Only Properties

  • range.startContainer: Node where the range begins.
  • range.startOffset: Number representing offset into startContainer.
  • range.endContainer: Node where the range terminates.
  • range.endOffset: Number representing offset into endContainer.
  • range.commonAncestorContainer: Deepest Node that contains both start and end containers.
  • range.toString(): String text contents within the range.

Related topics