# Cloning multiple elements

I want to clone every element at .dynamic-content1 and automatically increment itself and every id of its children to make it unique and also can remove the last cloned .dynamic-content.

<div class="dynamic-content1">
<div class="dynamic-wrapper">
<p><strong>Child | 1</strong></p>
<div class="dynamic-row">
<label>Fullname</label>
<div class="right">
<input type="text" name="chname1" id="chname1" />
</div>
</div>

<div class="dynamic-row">
<label>Place of Birth</label>
<div class="right">
<input type="text" name="chpob1" id="chpob1" />
</div>
</div>

<div class="dynamic-row">
<label>Date of Birth</label>
<div class="right">
<input type="text" class="datepicker" id="chdate1" name="chdate1" />
</div>
</div>

<div class="dynamic-row">
<label>Highest Education</label>
<div class="right">
<input type="text" name="chedu1" id="chedu1" />
</div>
</div>

<div class="dynamic-row">
<label>Occupation</label>
<div class="right">
<input type="text" name="chocc1" id="chocc1" />
</div>
</div>
</div>
</div>


The .dynamic-wrapper and .dynamic-row are just for styling purpose.

Actually I already can do this, but in a very very dirty way and not very effective. Is there any way you can show me using .clone()?

My way to achieve this

-

## migrated from stackoverflow.comDec 5 '12 at 13:46

This question came from our site for professional and enthusiast programmers.

I'm not sure I get the problem. Are you using clone ? –  dystroy Dec 5 '12 at 12:31
No, actually I'm using the tutorial at mkyong.com/jquery/… after using the tutorial I see my code takes too many lines, and looking for alternative using clone. –  Xtrader Dec 5 '12 at 12:33
Should this really have been migrated from SO ? –  dystroy Dec 5 '12 at 13:59
I don't think it should have been migrated, but it fits here in CR as well. –  ANeves Dec 5 '12 at 16:49

Making the clone is simple :

var $clone =$('.dynamic-content1').clone();


To change the id of the cloned elements, you could do this :

\$clone.find('[id]').each(function(){this.id+='someotherpart'});


Demonstration (open the console to check the id)

-
Hmm, I'm still a bit confused while modifying it to be what i wanted to, can you look into my working code without clone? What I want to achieve is looks like this jsfiddle.net/R2c5K –  Xtrader Dec 5 '12 at 13:16
I made a new version : jsfiddle.net/nJBRd. When you clone an object multiple time, you have to pay attention to cloning only the first one (hence the :eq(0)). –  dystroy Dec 5 '12 at 13:55