Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Deep copy of DOM element with jQuery

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!

like image 701
BlackWolf Avatar asked Oct 16 '13 20:10

BlackWolf


People also ask

How do you clone an object in jQuery?

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);

How do I copy a dom?

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.

How do you duplicate an element?

To duplicate an element: Select the element. Click Option + Drag (on Mac )or Alt + Drag (on Windows)

How do you duplicate an element in Javascript?

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.


1 Answers

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));
like image 110
1j01 Avatar answered Sep 22 '22 00:09

1j01