Is it possible to clone html element objects in Ja

2019-01-04 01:56发布

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

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

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-04 02:28

Try this:

$('#foo1').html($('#foo2').children().clone());
查看更多
Anthone
3楼-- · 2019-01-04 02:33

The jQuery way (not the most efficient):

Look at the clone() method of JQuery

Using your code you can do something like that:

$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want
查看更多
Juvenile、少年°
4楼-- · 2019-01-04 02:35

In one line:

$('#selector').clone().attr('id','newid').appendTo('#newPlace');
查看更多
放我归山
5楼-- · 2019-01-04 02:38

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/

查看更多
男人必须洒脱
6楼-- · 2019-01-04 02:38

It's actually very easy in jQuery:

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

Change .appendTo() of course...

查看更多
做个烂人
7楼-- · 2019-01-04 02:41

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

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

FIDDLE HERE

查看更多
登录 后发表回答