什么是仅使用javascript复制文档对象的最简单方法 [英] what is the easiest way to make a copy of document object with javascript only

查看:55
本文介绍了什么是仅使用javascript复制文档对象的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档对象的副本在复制后应与...文档对象一样,但应与实际的dom引用完全分开.我的意思是-如果我们将此文档副本另存为 var documentCopy documentCopy,则应能够像 document 可以,但是对其的修改不会影响原始的 document 对象.

The copy of the document object should act just like ... document object after its copied, but totally detached from the actual dom reference. What I mean by that is -- if we save this copy of document as var documentCopy documentCopy should be able to run .getElementsByClass('xx') on itself just as document would able to, but the modification of it will not affect the original document object.

有可能吗?

除jQuery外,我对所有库都开放.

I am open to all libraries except jQuery.

推荐答案

您可以使用 .cloneNode(true) 以获得DOM的完整副本.诸如自定义属性之类的东西不会被复制.可能没什么大问题,因为无论如何您都应该使用 data-属性和 dataset 属性,这些属性将与克隆一起复制.

You can use .cloneNode(true) to get a full copy of the DOM. Some things like custom properties won't get copied though. Probably not much of an issue, since you should use data- attributes and the dataset property anyway, which will get copied with the clone.

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 参数使它成为深度复制,而不仅仅是克隆外部元素.

The true argument makes it a deep copy instead of just cloning the outer element.

这篇关于什么是仅使用javascript复制文档对象的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆