Shivam
Shivam

Reputation: 2248

Concatenate loop within loop in jQuery?

I am trying to create a grid like structure. I want to create a loop within a loop and append divs based on if it is a column or a row. Below is my attempt:

for (var row = 0; row < 8; row++) {
    $('#board').append('<div class="row">'+ row +'</div>');  
}

What I would like to replicate in plain Javascript (code is most likely incorrect, I just want to show an example of what I want):

var board = document.getElementById('board');

for (var row = 0; row < 8; row++) {
    board.write('<div class="row">');
    for(var col = 0; col < 8; col++) {
        var row = document.getElementsByClassName('row');
        row.write('<div class="piece">'+col+'</div>')
    }
    board.write('</div>');
}

It would be useful if I could somehow replicate the document.write() method in jQuery. .append() did not work correctly for me when I tried to include a forloop.

Upvotes: 0

Views: 1631

Answers (3)

Try the following - if you need to manipulate DOM more specifically, then use JQuery

var board = document.getElementById('board'),
    html = '';

for (var row = 0; row < 8; row++) {
    html += '<div class="row">';
    for(var col = 0; col < 8; col++) {
        html += '<div class="piece">'+col+'</div>';
    }
    html += '</div>';
}

board.innerHTML = html;

Or with JQuery:

var board = $('#board');
...
board.append($(html));

Upvotes: 1

Sumurai8
Sumurai8

Reputation: 20737

What I understand you want to end up with a structure like this:

<div id="board">
  <div class="row">
    <div class="piece"></div>
    <div class="piece"></div>
    <div class="piece"></div>
    (...)
  </div>
  (...)
</div>

Let's assume you already have a board (<div id="board"></div>).

for( var row = 0; row < 8; row++ ) {
  //Create a row
  $row = $('<div class="row"></div>');

  //Stuff 8 pieces in that row
  for( var col = 0; col < 8; col++ ) {
    $row.append( $('<div class="piece">' + col + '</div>') );
  }

  //Add the row to the board
  $('#board').append( $row );
}

Edit: In your case you can even simplify it to:

//Stuff 8 rows in the board
for( var row = 0; row < 8; row++ ) {
  $('#board').append( $('<div class="row"></div>') );
}

//Stuff 8 pieces in every of the 8 rows
//This can be done because the piece is the same for every row
for( var col = 0; col < 8; col++ ) {
  $('.row').append( $('<div class="piece">' + col + '</div>') );
}

jsFiddle: http://jsfiddle.net/3jGnF/

Upvotes: 1

Dziad Borowy
Dziad Borowy

Reputation: 12579

You just need to loop through rows and then cells to build a single html string and than append it only once:

var rows = [], cells = [];
for (var row = 0; row < 8; row++) {
    cells = [];
    for (var cell = 0; cell < 8; cell++) {
        cells.push('<div class="piece">'+ row +'</div>');
    }
    rows.push('<div class="row">' + cells.join('') + '</div>');
}

$('#board').html(rows.join(''));

DEMO HERE

Upvotes: 2

Related Questions