← 中文资源

简体中文版本

createRange 把 DOM 节点搬进 DocumentFragment

document.createRange 不依赖用户选区:selectNodeContents 圈定范围,cloneContents 预览副本,extractContents 剪出碎片后 append 即完成搬移。

阅读英文原文

实现说明

演示用的数据放在这几个模块级绑定中:source、target、range、fragment。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。
  • 每一步打印都带着自己的标签:in range:、source now:、target now:。

常见问题

「createRange 把 DOM 节点搬进 DocumentFragment」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

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

代码示例

// 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);