使用JavaScript制作文档对象的最简单方法是什么?

7
文档对象的副本应该像文档对象一样运作,但是与实际的dom引用完全分离。我的意思是,如果我们将这个文档的副本保存为var documentCopy,那么documentCopy应该能够像document一样在自身上运行.getElementsByClass('xx'),但它的修改不会影响原始的document对象。
这是否可能?
我可以接受除了jQuery之外的所有库。

2
真正的问题是,你为什么需要这样的东西? - adeneo
1
@adeneo 生成 PDF 文档 - ey dee ey em
将其保存在函数中,在外部范围内引用它。但是,这种方式不起作用,实际的DOM仍然被引用。 - ey dee ey em
如果您提供一些有关您的预期目的的详细信息,可能会有比尝试在JavaScript中复制文档对象更好的方法。 - Anony372
@Ezeewei,克隆“document”如何帮助您生成PDF文档? - Koushik Chatterjee
@KoushikChatterjee 抱歉,那是公司的机密,不是我的工作。 - ey dee ey em
2个回答

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);
pre {
  font-size: 1.4em;
}
<div class="foo"></div>
<div class="foo"></div>

<pre></pre>

< p > true 参数表示进行深度复制,而不仅仅是克隆外部元素。 < /p >

1
document 关键字将为您提供对文档的引用 -- 而不是副本。因此,在您的示例中,对 documentCopy 的更改影响原始文档。
在幕后,浏览器将文档层次结构维护为链接的“节点”对象,因此没有一种很好的方法可以仅“复制”所有对象及其当前状态。
为了获得节点对象的新“副本”,您需要将它们的 HTML 内容作为字符串获取,然后使用该 HTML 标记将新节点插入到 DOM 中:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接