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

Eze*_*wei 7 javascript clone document object

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

那可能吗?

我对除 jQuery 之外的所有库都持开放态度。

spa*_*nky 7

您可以使用.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);
Run Code Online (Sandbox Code Playgroud)
pre {
  font-size: 1.4em;
}
Run Code Online (Sandbox Code Playgroud)
<div class="foo"></div>
<div class="foo"></div>

<pre></pre>
Run Code Online (Sandbox Code Playgroud)

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