I’ve ran into a problem when cloning a template div to create elements for a dataset.
The problem is that classes accumulate between creating the elements for each data record.
Example JS:
$(document).ready(function(){
var data = [
{cls: 'test1',text:'test1'},
{cls: 'test2',text:'test2'},
{cls: 'test3',text:'test3'}
];
for(var x in data)
{
var item = $('#itemTemplate').clone().removeClass('template');
item.addClass(data[x].cls).html(data[x].text);
$('#test-container').prepend(item);
}
});
And the HTML body:
<div id="test-container">
</div>
<div id="itemTemplate" class="template">
</div>
This produces:
<div id="test-container">
<div id="itemTemplate" class="test1 test2 test3">test3</div>
<div id="itemTemplate" class="test1 test2">test2</div>
<div id="itemTemplate" class="test1">test1</div>
</div>
Notice the test1 test2 test3 where it should just be test3. Am I missing something or just got it plain wrong?
Tested in jQuery 1.7 & 1.6.4.
you should also remove the id from the cloned elements. else it doesn’t know which one he needs to clone