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

耗尽温柔 提交于 2019-11-26 16:14:10
Boris Guéry

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
annakata

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.

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

Try this:

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

In one line:

$('#selector').clone().attr('id','newid').appendTo('#newPlace');

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!