The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).
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.
to add the div. Then we can clone the div by writing: const div = document. getElementById('foo') const clone = div.
With native JavaScript:
newelement = element.cloneNode(bool)
where the Boolean indicates whether to clone child nodes or not.
Here is the complete documentation on MDN.
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 jQuery clone() method (not the most efficient):
$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want
Yes, you can copy children of one element and paste them into the other element:
var foo1 = jQuery('#foo1');
var foo2 = jQuery('#foo2');
foo1.html(foo2.children().clone());
Proof: http://jsfiddle.net/de9kc/
It's actually very easy in jQuery:
$("#ddl_1").clone().attr("id",newId).appendTo("body");
Change .appendTo() of course...
You can use clone() method to create a copy..
$('#foo1').html( $('#foo2 > div').clone());
FIDDLE HERE
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