2017-08-29 63 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>

相關問題