仅使用 javascript 制作文档对象副本的最简单方法是什么

what is the easiest way to make a copy of document object with javascript only

文档对象的副本在复制后应该像...文档对象一样,但与实际的 dom 引用完全分离。我的意思是——如果我们将此文档副本保存为 var documentCopy documentCopy 应该能够 运行 .getElementsByClass('xx') 自身,就像 document 能够做到的一样,但是对它的修改不会影响原来的document对象。

这可能吗?

我对除 jQuery 以外的所有图书馆开放。

您可以使用 .cloneNode(true) 获取 DOM 的完整副本。但是,自定义属性等某些内容不会被复制。可能不是什么大问题,因为无论如何您都应该使用 data- 属性和 dataset 属性,它们将随克隆一起复制。

var pre = document.querySelector("pre");

// custom properties will not get cloned
pre.customProp = "foobar";

// data- attributes/properties will get cloned
pre.dataset.foo = "bar";

// clone the document
var documentCopy = document.cloneNode(true);

// show that DOM selection works on the copy
console.log("clone found ", documentCopy.getElementsByClassName("foo").length, "'foo' nodes");

// the custom property did not get cloned
console.log("custom prop:", documentCopy.querySelector("pre").customProp);

// but the dataset property did
console.log("dataset prop:", documentCopy.querySelector("pre").dataset.foo);
pre {
  font-size: 1.4em;
}
<div class="foo"></div>
<div class="foo"></div>

<pre></pre>

true 参数使其成为深拷贝,而不是仅仅克隆外部元素。

document 关键字将为您提供 reference 文档 -- 而不是副本。因此,在您的示例中,对 documentCopy 的更改会 影响原始文档。

在后台,浏览器将文档层次结构维护为链接的 "node" 对象,因此没有很好的方法只 "copy" 所有对象及其当前状态。

为了获得新的 "copies" 节点对象,您需要将它们的 HTML 内容作为字符串获取,然后使用 [=] 将新节点插入 DOM 32=] 标记:

// get the original body HTML
var bodyHTML = document.body.innerHTML;

// create a new div and set its contents
var copiedNode = document.createElement("div");
copiedNode.innerHTML = bodyHTML;

// inser the new nodes
document.body.appendChild(copiedNode);

// modify the copied nodes
copiedNode.firstElementChild.setAttribute("style", "color: blue");
<p style="color: red;">paragraph one</p>