views:

188

answers:

2

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 element, I want to clone it without its value and change its id and name attribute to "exmple2" if it was named "example" previously.

I would appreciate any help on this and any other implementation I can use to add more elements to my html form that already exists on the page.

Thanks all

+7  A: 

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");
peirix
clone() docs: http://docs.jquery.com/Manipulation/clone
codeape
+1  A: 

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).

OIS
you can change both id and name inside same `attr()`-call...makes it a bit shorter and nicer (:
peirix