Search code examples
javascriptobjectclonedocument

what is the easiest way to make a copy of document object with javascript only


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.

Is that possible?

I am open to all libraries except jQuery.


Solution

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

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