If what you are looking to do is have uniquely generated IDs, then I suggest using a GUID. Support for GUID generation is not native in JS, but this post provides the following function for their creation:
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
You can customize the return statement to use your desired GUID format. You would basically have something like the following though:
$('#item-list').append('<div id="' + guid() + '" class="item">New item</div>');
I grant you that the performance of GUID creation is less than that of incrementing and concatenating, but GUIDs give you highly "unique" (extremely unlikely to get two of the same) IDs and generate them without having to create loops. Support for GUIDS is usually included in back-end languages, like PHP and C#, as well as database scripting languages, like SQL and MySQL. As such, they can be a pretty powerful tool, depending on the task at hand.
The below is a little demo:
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
$(document).ready(function() {
var $itemList = $('#item-list');
var $itemIdList = $('#item-id-list');
$("#btnAddElement").on("click", function() {
$itemList.append('<div id="' + guid() + '" class="item">New item</div>');
$itemIdList.append('<li>' + $itemList.children().last().attr('id') + '</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div id="item-list"></div>
<ol id="item-id-list"></ol>
</div>
<button type="button" id="btnAddElement">Add an element</button>