pedram pedram - 5 months ago 13
HTML Question

Append element to each div in order

Well, I'm trying to make a logo with

css
and
html
and here is the output:

jsFiddle

now I want to make this with
jquery
and create all
div
dynamically. this is what I have done so far:

var count = 13;
var n = 0;

for(var i = 0; i < count; i++){
n++;
$('<div class="LogoRow" id="LogoRow-'+n+'"></div>').appendTo('#Logo');
}

$('#Logo .LogoRow:nth-child(odd)').addClass('LogoRowLeft');
$('#Logo .LogoRow:nth-child(even)').addClass('LogoRowRight');

$('.LogoRow').each(function(){
var count = 8;
for(var i = 0; i < count; i++){
$(this).append('<span class="LogoTriangle"></span>');
}
});


jsFiddle

I appended 13
LogoRow
to
#Logo
then 8
LogoTriangle
to each
LogoRow
but the problem is it should append
LogoTriangle
differently, like this:

append 8 `LogoTriangle` to `LogoRow` nth child 1
append 7 `LogoTriangle` to `LogoRow` nth child 2 and 3
append 6 `LogoTriangle` to `LogoRow` nth child 4 and 5
append 5 `LogoTriangle` to `LogoRow` nth child 6 and 7
append 4 `LogoTriangle` to `LogoRow` nth child 8 and 9
append 3 `LogoTriangle` to `LogoRow` nth child 10 and 11
append 2 `LogoTriangle` to `LogoRow` nth child 12 and 13
append 1 `LogoTriangle` to `LogoRow` nth child 14 and 15


but i have no idea how can i append an element to another element like this. any suggest?

Answer

Move the count = 8 outside the loop and change the condition to decrease the value like following.

count = 8;
$('.LogoRow').each(function(k) {
  console.log(count);
  for (var i = 0; i < count; i++) {
    $(this).append('<span class="LogoTriangle"></span>');
  }
  if (k == 0 || (k > 0 && k % 2 == 0))
    count--;
});

DEMO

Comments