136

I have a html element (like select box input field) in a table. Now I want to copy the object and generate a new one out of the copy, and that with JavaScript or jQuery. I think this should work somehow but I'm a little bit clueless at the moment.

Something like this (pseudo code):

oldDdl = $("#ddl_1").get(); 

newDdl = oldDdl;

oldDdl.attr('id', newId);

oldDdl.html();
1

10 Answers 10

348

The modern approach is to use the cloneNode function:

let new_element = element.cloneNode(true);

where the Boolean indicates whether to also clone its child nodes or not.

Afterwards, you can add the cloned element to DOM somewhere. For example, you can use after() to insert the new element right after the original element:

element.after(new_element);

Compatibility:

Browser compatibility for Element.after

Browser compatibility for Node.cloneNode

5
  • 67
    best answer. don´t use jquery where you don´t need it.
    – andyrandy
    Mar 16, 2014 at 15:50
  • Looks good ... but browser compatibility is questionable as of today. Feb 4, 2015 at 20:24
  • 16
    @AniketSuryavanshi I'm not sure about February 4th in particular, but compatibility looks perfect today
    – user1846065
    Apr 4, 2015 at 18:41
  • 4
    IDs and names will be duplicated. IDs NEED to be changed, names COULD be left as they are if duplicate names are expected.
    – przemo_li
    Aug 28, 2017 at 9:05
  • Too bad you lose all attributes :/ Sep 23, 2019 at 12:49
91

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
1
  • 45
    It is VERY important to modify the ID when you clone an element. Oct 9, 2012 at 10:47
17

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/

1
  • Duplicate IDs will be an issue with Your approach
    – przemo_li
    Aug 28, 2017 at 9:05
3

It's actually very easy in jQuery:

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

Change .appendTo() of course...

0
3

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

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

FIDDLE HERE

3

Get the HTML of the element to clone with .innerHTML, and then just make a new object by means of createElement()...

var html = document.getElementById('test').innerHTML;
var clone = document.createElement('span');
clone.innerHTML = html;

In general, clone() functions must be coded by, or understood by, the cloner. For example, let's clone this: <div>Hello, <span>name!</span></div>. If I delete the clone's <span> tags, should it also delete the original's span tags? If both are deleted, the object references were cloned; if only one set is deleted, the object references are brand-new instantiations. In some cases you want one, in others the other.

In HTML, typically, you'll want anything cloned to be referentially self-contained. The best way to make sure these new references are contained properly is to have the same innerHTML rerun and re-understood by the browser within a new element. Better than working to solve your problem, you should know exactly how it's doing its cloning...

Full Working Demo:

function cloneElement() {
    var html = document.getElementById('test').innerHTML;
    var clone = document.createElement('span');
    clone.innerHTML = html;
    document.getElementById('clones').appendChild(clone);
}
<span id="test">Hello!!!</span><br><br>

<span id="clones"></span><br><br>

<input type="button" onclick="cloneElement();" value="Click Here to Clone an Element">

3

Vanilla JS approach on what you are trying to do

const oldDdl = document.querySelector('#ddl_1');

const newDdl = oldDdl.cloneNode(true);

oldDdl.setAttribute('id','newId');

const oldDdlHtml = oldDdl.innerHTML;
1

Try this:

$('#foo1').html($('#foo2').children().clone());
0
0

In one line:

$('#selector').clone().attr('id','newid').appendTo('#newPlace');
1
  • 1
    I don't think that will help as your attribute value is a string that won't change. Aug 19, 2011 at 20:18
0

You need to select "#foo2" as your selector. Then, get it with 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 the jsfiddle: http://jsfiddle.net/fritzdenim/DhCjf/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.