John John - 4 months ago 40
jQuery Question

Duplicate Div With New ID

I got a function that duplicates a div and changes the new divs id to +1

function duplicate(){
// Get content to clone
var line_to_clone = $('#fields_1').html();
// Get new line id
var next_line_id = $('.items').length + 1;
// Add the div container
var line_to_clone = '<div id="fields_' + next_line_id + '" class="items">' + line_to_clone + '</div>';
// Create new line
var new_line = line_to_clone.replace(/_1/gi, "_" + next_line_id);
// Render it
$('#renderer').append(new_line);
}


It will work but the ids are wrong when it hits 10

<div id="fields_8" class="items">
<div id="fields_9" class="items">
<div id="fields_100" class="items">
<div id="fields_111" class="items">
<div id="fields_122" class="items">
<div id="fields_133" class="items">
<div id="fields_144" class="items">

Answer

Please check below snippet.

function duplicate(){
// Get content to clone
var line_to_clone = $('#fields_1').html();
// Get new line id
var next_line_id = $('.items').length + 1;
  
// Add the div container
var line_to_clone = '<div id="fields_' + next_line_id + '" class="items">' + line_to_clone + '</div>';
// Create new line

// Render it
$('#renderer').append(line_to_clone);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="renderer">
  <div id="fields_1" class="items">123</div>
</div>
<input type="button" value="add" onclick="duplicate()"/>