2

I am working on a project that involves creating our own version of Conway's "Game of Life". I went for a simple representation of my 20x20 grid as many nested divs - the entire grid is a div, each row is a div, and each cell within that is also a div.

My code is working just fine, but I am wondering in retrospect if there was an easier way to create my divs using html/javascript/jquery other than brute-forcing copy-pasting it out. It's something I would naturally think to do with for-loops if it were not HTML, which I don't know very much about.

Is there an easy way to do this?

admdrew
  • 3,790
  • 4
  • 27
  • 39

2 Answers2

0

you can create elements using jquery. So if your trying to create a div element you can do this for example:

var grid = $('<div class="grid"></div>');
for (var i = 0; i < 20; i++) { 
 var row = $('<div class="row"></div>')  
 for (var j = 0; j < 20; k++) {
   var cell = $('<div class="cell"></div>');
   row.append(cell);
 }
 grid.append(row);
}

So if you do something like that you can create your grid using JS

smk1992
  • 71
  • 3
0

Using for loops and innerHTML:

function makeTable(width, height) {
    var row, col, table = document.createElement('div'), html = '';
    for (row = 0; row < height; row += 1) {
        html += '<div class="row">';
        for (col = 0; col < width; col += 1) {
            html += '<div class="cell" id="c' + row + '_' + col + '"></div>';
        }
        html += '</div>';
    }
    table.className = 'game';
    table.innerHTML = html;
    return table;
}
document.getElementById('target').appendChild(makeTable(20, 20));

You can also convert the HTML code that you're building up into a DOM tree with jQuery via $('html_code_here') which has the same effect as placing it as the innerHTML of a DIV element; this just uses that to generate the table element. Individual cells are given indexes like c_1_1, c_1_2, ..., c_20_20 for your addressing.

CR Drost
  • 9,637
  • 1
  • 25
  • 36