2017-08-29 64 views
0

该文档对象的副本应该像复制后的文档对象一样,但完全脱离实际的dom引用。我的意思是 - 如果我们将这份文档保存为var documentCopy documentCopy应该能够在其自身上运行.getElementsByClass('xx')就像document能够,但修改它不会影响原始document对象。使用javascript制作文档对象副本的最简单方法是什么

这可能吗?

我对除jQuery以外的所有库都开放。

+2

真正的问题是为什么地球上你会需要类似的东西? – adeneo

+0

@adeneo生成pdf文档 – Ezeewei

+1

你试过了什么? – j08691

回答

2

您可以使用.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参数使得它的深层副本,而不是仅仅克隆外元件。

+0

绝对真棒回答! – Ezeewei

+0

很高兴帮助。 :-) – spanky

0

document关键字会给你reference的文件 - 不是副本。所以在你的例子中,对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>

相关问题