3

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

3 Answers 3

10

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.