I was trying to mirror/clone a div into another div but I couldn't find any solutions to this online. What I mean by clone is replicate everything live from one div to another. An example of this is when you hover on icons in your taskbar on Windows OS it shows you what is happening on that specific GUI. How can I achieve this? If there are no ways of live cloning , screenshotting that specific div and showing it on a separate div would be fine. One important thing to keep in mind is that the div to be cloned could contain elements like Images, text, videos, Iframes, etc... Any help on this or a nudge in the right direction is much appreciated. Thanks in advance.
Code Updated:
function testFun() {
let source = document.querySelector('#testDiv');
let dest = document.querySelector('#testDivClone');
let clone = source.cloneNode(true); // true -> deep cloning, i.e. the whole subtree
dest.appendChild(clone);
}
#testDiv {
position: absolute;
top: 10%;
width: 30%;
height: 60%;
background-color: green;
}
#testDiv iframe {
width: 100%;
height: 100%;
}
#testDivClone {
position: absolute;
top: 10%;
right: 5%;
width: 30%;
height: 60%;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.0/html2canvas.min.js" integrity="sha512-UcDEnmFoMh0dYHu0wGsf5SKB7z7i5j3GuXHCnb3i4s44hfctoLihr896bxM0zL7jGkcHQXXrJsFIL62ehtd6yQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id='testDiv'>
<p>
Clone This
</p>
</div>
<canvas id='testDivClone'>
</canvas>
<button onclick="testFun()">
click
</button>
CodePudding user response:
Cloning a DOM element can be achived by using the cloneNode method of the Node interface.
In your case:
<div id="testDiv">
<!-- ... -->
</div>
<div id="testDivClone"> <!-- Not a canvas element anymore -->
</div>
let source = document.querySelector('#testDiv');
let dest = document.querySelector('#testDivClone');
let clone = source.cloneNode(true); // true -> deep cloning, i.e. the whole subtree
dest.appendChild(clone);
However, be aware that this will not clone any event listeners previously added to the source node or any of its children. Additionally, cloning nodes may lead to duplicate elements with the same ID.
See https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode for more information.
