文档对象的副本应该像 ... 复制后的文档对象一样,但与实际的 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
参数使其成为深拷贝,而不仅仅是克隆外部元素。
关于javascript - 仅使用 javascript 制作文档对象副本的最简单方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45946695/