Simple way
1 2 3 4 5 6 |
var cloneCount = 1; $("button").click(function(){ $("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id"); }); |
A more complicated way is below…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <button id="doit">CLICK TO CLONE</button> <div id="div1">div1</div> <div id="div2">div2</div> <div id="div3">div3</div> <script id="jsbin-javascript"> $(function($) { $('#doit').click(function(){ // get the last DIV which ID starts with ^= "div" var $div = $('div[id^="div"]:last'); // Read the Number from that DIV's ID (i.e: 3 from "div3") // And increment that number by 1 var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1; // Clone it and assign the new ID (i.e: from num 4 to ID "div4") var $new = $div.clone().prop('id', 'div'+num ); // Finally insert $klon wherever you want $div.after( $new.text('div'+num) ); }); }); </script> |