Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Editing the DOM with Range

Cut, insert, and delete DOM content. Learn how to position a range, collapse it to a single point, and tell what `cloneRange()` copies.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

range.extractContents() → DocumentFragment
range.insertNode(newNode) → undefined
range.deleteContents() → undefined
range.setStartAfter(referenceNode) → undefined
range.collapse() → undefined
range.collapse(toStart) → undefined
range.cloneRange() → Range

Range.extractContents/insertNode/deleteContents/setStartAfter/collapse/cloneRange groups six instance methods for editing or positioning a live DOM range. Its start and end are each a container node and an offset. In a text node, the offset counts UTF-16 code units; in an element, it counts preceding child nodes, not just child elements. Range belongs to the DOM, not ECMAScript 2024; the runtime must provide a DOM.

extractContents() removes the range content and returns a DocumentFragment. Fully contained nodes are moved into it; selected portions of text are copied, and partially contained elements are cloned as needed to preserve their structure. deleteContents() removes the content without returning a fragment (undefined). Both operations leave the range collapsed. If it is already collapsed, extraction returns an empty fragment and deletion does nothing.

insertNode(newNode) inserts at the start boundary without replacing the range content. A text node at the boundary is split at that point. Passing a DocumentFragment moves its children and leaves it empty. Insertion can expand a collapsed range. An invalid tree hierarchy can cause HierarchyRequestError. Insertion does not sanitize content; put untrusted plain text in a text node rather than parsing it as HTML.

setStartAfter(referenceNode) sets the start immediately after the reference node, in its parent. A parentless reference node causes InvalidNodeTypeError. If the new start is after the end or in a different tree, the end also moves to that point. collapse(true) collapses to the start; collapse(false) and collapse() collapse to the end. These two methods and insertNode() return undefined.

cloneRange() returns a separate Range with initially identical boundaries, without copying any nodes. Setting a boundary on one range does not directly reposition the other, but both are live: DOM mutations can adjust the boundaries of both. The clone is not a snapshot of the content.

Examples

<!doctype html>
<meta charset="utf-8">
<title>Editing the DOM with Range</title>
<script>
(() => {
  const source = document.createElement('p');
  const target = document.createElement('p');
  const item = document.createElement('em');
  item.textContent = 'B';
  source.append('A', item, 'C');
  target.textContent = 'XY';

  const cut = document.createRange();
  cut.selectNode(item);
  const copy = cut.cloneRange();
  copy.collapse(true);
  console.log(`before: ${cut.toString()} / ${copy.collapsed}`);

  const fragment = cut.extractContents();
  const edit = document.createRange();
  edit.setStart(target.firstChild, 1);
  edit.collapse(true);
  edit.insertNode(fragment);
  console.log(`moved: ${source.textContent} / ${target.textContent} / ${fragment.childNodes.length}`);

  edit.setStartAfter(item);
  edit.collapse(true);
  edit.setEnd(target, target.childNodes.length);
  edit.deleteContents();
  console.log(`final: ${target.textContent} / ${edit.collapsed}`);
})();
</script>

Result

before: B / true
moved: AC / XBY / 0
final: XB / true

Save the example as an HTML file, open it in a browser, and check the developer console. Collapsing the copy leaves `B` in the original range. The extracted node goes between `X` and `Y`, the fragment empties, and `Y` is then deleted.

Related lessons

  • JavaScript · Lesson 33 · Intermediate · Version: 3

Sources