createRange Moves DOM Nodes As Fragments

Select a DOM span with document.createRange, preview it with cloneContents, and move whole node sets with extractContents plus append.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
// document.createRange selects a span of the DOM without any user
// selection; cloneContents copies it, extractContents cuts it out
const source = document.querySelector('#source');
const target = document.querySelector('#target');

const range = document.createRange();
range.selectNodeContents(source);
console.log('in range:', range.cloneContents().children.length);

// extractContents removes the range from the tree and hands back a
// DocumentFragment, so moving nodes is append and done
const fragment = range.extractContents();
target.append(fragment);

console.log('source now:', source.children.length);
console.log('target now:', target.children.length);

How it works

Demo state sits in top-level bindings: source, target, range, fragment.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

Output lines are prefixed (in range:, source now:, target now:), making each step’s impact easy to trace.

The key statements, annotated

const source = document.querySelector('#source');
const target = document.querySelector('#target');
const fragment = range.extractContents();

Interactive Tools for This Topic

FAQ

Does createRange Moves DOM Nodes As Fragments run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.