Is there a way to clone HTML elements using JQuery?
However, I want to be able to assign the cloned elements new attributes \"id, name\". So if I had a textfield ele
Once you have a cloned element you can change it any way you want to
Updated: Didn't notice that you wanted to change both name and id.
$("#example").clone()
.attr({"id":"example2", "name":"example2"})
.html("new content")
.appendTo("#container");
Here is sample of creating clone using jquery.
Html code::
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div style="margin: 10px 10px 10px 0px" id="addNewDiv"> <table style="width: 100%" id="maintable" class="cloneTable">
<tr><td><input type="text" name="text" id="text"/></td></tr>
</table></div>
<input type="button" value="Add New Div" onclick="addNewDiv();" style="background-color: #3E8DE1; color: white;" />
Javascript code::
var count=1;
function addNewDiv(){
var $clone = $(".cloneTable:first").clone(true);
$clone.find(':text,:file').each(function() {
$(this).attr('id',($(this).attr("id")+count));
$(this).val('');
});
$clone.find("a").each(function() {
$(this).val('').attr('id', function(_, id) {
return count;
});
});
$clone.find("span").each(function() {
$(this).attr({
id: $(this).attr("id") + count
});
});
$clone.attr( 'id', function() {
return this.id + count; })
.appendTo('#addNewDiv');
count=count+1;
}
Here is the link of fiddle of same example. Clone Fiddle
documentation
I use jQuery over $ so it works with other libraries. Here is an example on an input text field.
jQuery('#example').clone().val('').attr('id', 'exmple2').attr('name', 'exmple2').insertAfter('#example');
If you want to clone the event handlers as well, you have to use clone(true).