Is it possible to create a clone/copy of a DOM element in jQuery without cloning its content? I need to split the content of a div into two separate divs with the same attributes. So for example I need to change:
<div class="someclass" someattr="someval">
this is the first sentence. this is the second sentence.
</div>
into something like:
<div class="someclass" someattr="someval">
this is the first sentence.
</div>
<div class="someclass" someattr="someval">
this is the second sentence.
</div>
How exactly the content is split is rather complicated, but this is basically what I need to do. Obviously, creating a clone without content can be achieved using:
$(el).clone().empty();
But since my element can become rather large, I would like to get rid of the overhead of unnecessarily cloning the element content. Ideas? Thanks!
Syntax: // Create a clone of the object using the extend() method let newObj = jQuery. extend({}, obj); // Create a deep clone of the object using the deep parameter let newDeepObj = jQuery. extend(true, {}, obj);
Right click on a node and select Copy. You can paste in your code editor, or for prototyping, you can paste the DOM node elsewhere in the DOM tree. The pasted node is inserted as a child of the currently selected node.
To duplicate an element: Select the element. Click Option + Drag (on Mac )or Alt + Drag (on Windows)
You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.
Just go around jQuery for this operation, as long as you don't need to keep (non-attribute-based) event listeners or other data.
var $clone = $(el.cloneNode(false));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With