user1324780 user1324780 - 1 year ago 110
jQuery Question

How to JQuery clone() and change id

I need to clone the id and then add a number after it like so id1, id2, etc. Everytime you hit clone you put the clone after the latest number of the id.


Answer Source

jsBin demo

<div id="klon1"> KLON1 </div>
<div id="klon2"> KLON2 </div>
<div id="klon3"> KLON3 </div>
<!-- we need a "klon4" here -->

// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');

// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// 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 "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );

// >>> Append $klon wherever you want