Is it possible to clone html element objects in JavaScript / jQuery?

I am looking for some tips on how to solve my problem.

I have an html element (e.g. select box input field) in a table. Now I want to copy the object and generate a new one from the copy, as well as using JavaScript or jQuery. I think this should work somehow, but I'm a little clueless at the moment.

Something like this (pseudo code):

oldDdl = $("#ddl_1").get(); newDdl = oldDdl; oldDdl.attr('id', newId); oldDdl.html(); 
+84
javascript jquery clone elements
May 28 '09 at 2:58 p.m.
source share
8 answers

Using your code, you can do something like this in plain JavaScript using the cloneNode () method:

 // Create a clone of element with id ddl_1: let clone = document.querySelector('#ddl_1').cloneNode( true ); // Change the id attribute of the newly created element: clone.setAttribute( 'id', newId ); // Append the newly created element on element p document.querySelector('p').appendChild( clone ); 

Or using the jQuery clone () method (not the most efficient):

 $('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want 
+35
May 28 '09 at 2:59 p.m.
source share

With native JavaScript:

 newelement = element.cloneNode(bool) 

where a boolean value indicates whether to clone child nodes or not.

Here is the complete MDN documentation .

+268
May 28 '09 at 15:01
source share

Yes, you can copy children of one element and paste them into another element:

 var foo1 = jQuery('#foo1'); var foo2 = jQuery('#foo2'); foo1.html(foo2.children().clone()); 

Proof: http://jsfiddle.net/de9kc/

+15
Sep 28
source share

This is actually very simple in jQuery:

 $("#ddl_1").clone().attr("id",newId).appendTo("body"); 

Change .appendTo (), of course ...

+3
May 28 '09 at 15:00
source share

You can use the clone () method to create a copy.

 $('#foo1').html( $('#foo2 > div').clone())​; 

FIDDLE HERE

+2
Sep 28
source share

Try the following:

 $('#foo1').html($('#foo2').children().clone()); 
+1
Sep 28 '12 at 0:30
source share

In one line:

 $('#selector').clone().attr('id','newid').appendTo('#newPlace'); 
0
May 28 '09 at 15:01
source share

You need to select "# foo2" as a selector. Then enter html ().

Here is the html:

 <div id="foo1"> </div> <div id="foo2"> <div>Foo Here</div> </div> 

Here is the javascript:

 $("#foo2").click(function() { //alert("clicked"); var value=$(this).html(); $("#foo1").html(value); });​ 

Here is jsfiddle: http://jsfiddle.net/fritzdenim/DhCjf/

0
Sep 28
source share



All Articles