Reputation: 2725
Below is the code snippet. I am trying to create 16 x 16 grid divs and after every 15 I am trying to add a new line to it. To do the following I am adding the line class with the value 'change' on every 16th element. But it wouldn't work and all my first 240 elements will have the value 'change' for the 'line' class and the last 16 elements will have the value ''. As intended the console.log for the line displays the right behaviour (i.e. after every 15 nulls there is a change displayed)
$(document).ready( function() {
createDivs(16);
});
var createDivs = function (grids) {
for (var i = 0; i < grids; i++) {
var j = 0;
var line = '';
for (; j < grids; j++) {
var grid = '<div id=' + i + '' + j + '></div>';
if (j === 0) {
line = 'change';
}
console.log(line);
$('#container').append(grid);
$('#container > div').addClass('grid-class');
$('#container > div').addClass(line);
line = null;
}
}
}
Upvotes: 0
Views: 33
Reputation: 33409
$('#container').append(grid);
$('#container > div').addClass('grid-class');
$('#container > div').addClass(line);
You're selecting all of the divs, not just the most recent one. You could solve that simply by adding a :last
selector:
$('#container').append(grid);
$('#container > div:last').addClass('grid-class');
$('#container > div:last').addClass(line);
You could also simplify this by doing it all on a jQuery object created out of grid
:
$(grid).addClass('grid-class').addClass(line).appendTo('#container');
Upvotes: 1
Reputation: 36438
This:
$('#container > div').addClass(line);
will add that class to every single div matching the selector. When line
is null
, nothing new is added, but neither is anything deleted.
A cleaned-up variant, also no longer repeatedly adding grid-class
to every single div
, would be:
var ctr = $('#container');
for (var i = 0; i < grids; i++) {
for (var j = 0; j < grids; j++) {
var grid = $('<div id=' + i + '' + j + '></div>')
.addClass('grid-class');
if (j == 0)
grid.addClass('change');
ctr.append(grid);
}
}
Upvotes: 2