Good morning, I have this code that should categorize numbers into odd and even categories. It does so by going through numbers and creating a new category when necessary. Right after a new category is created it is appended with a new row containing a number. The problem is that it tends to skip the first element of the new category (i.e 1 and 2 are not included in the corresponding categories).
I can solve this by searching for a category again(commented out code(jsfiddle l:12)), but I would like to get the newly created category element from addNewCategory function, is that possible?
var content = $('#content');
// add one row to the category
var addRow = function (number) {
var categoryId = (number % 2 == 0 ? 'even' : 'odd'),
$category = content.find('#category_' + categoryId)
;
// category exists?
if(!$category.length) {
$category = addNewCategory (number);
//$category = content.find('#category_' + categoryId);
}
// prepare new row
var row = '<div class="row">' + number + '</div>';
$category.append(row);
};
// add new category
var addNewCategory = function(number) {
var categoryId = (number % 2 == 0 ? 'even' : 'odd'),
category = '<div class="category" id="category_' + categoryId + '">' + categoryId + '</div>';
content.append(category);
return $(category);
};
// start
for(var i = 1; i < 10; i++) {
addRow(i);
}
jsfiddle: jsfiddle