How do I create a table using a loop?

The individual table rows are giving me a problem. I created what I want using divs, but I need to use a table instead of a div. My table has 220 cells, 10 rows and 22 columns. Each cell must have a meaning i

inside innerHTML

. Here it looks like I want to use Divs (although cell height and width shouldn't be set):

<!DOCTYPE html>
<html>
    <head>
        <style>
            #container{ 
            width:682px; height:310px; 
            background-color:#555; font-size:85%;
            }

            .cell { 
            width:30px; height:30px;
            background-color:#333; color:#ccc;
            float:left; margin-right:1px;
            margin-bottom:1px;
            }
        </style>
    </head>

    <body>
        <div id="container">
            <script>
                for( var i = 1; i <= 220; i++ ){
                    document.getElementById( 'container' ).innerHTML += 
                    '<div class="cell">' + i + '</div>'
                }
            </script>
        </div>
    </body>
</html>

      

http://jsfiddle.net/8r6619wL/

This is my attempt at starting from a table:

<script>
    for( var i = 0; i <= 10; i++ )
    {
        document.getElementById( 'table' ).innerHTML +=
        '<tr id = "row' + i + '"><td>...</td></tr>';
    }
</script>

      

But this code somehow dynamically creates a bunch of tbody elements. Thanks for the help as I am newb

+3


source to share


3 answers


You can do this with nested loops - one to add cells to each row and one to add rows to the table. JSFiddle

var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 10; row++) {
    tr = document.createElement('tr');
    for (cell = 0; cell < 22; cell++) {
        td = document.createElement('td');
        tr.appendChild(td);
        td.innerHTML = row * 22 + cell + 1;
    }
    table.appendChild(tr);
}
document.getElementById('container').appendChild(table);

      

Alternatively , you can create an empty string of 22 cells, clone it 10 times, and then add numbers to the cells.



var table = document.createElement('table'),
    tr = document.createElement('tr'),
    cells, i;
for (i = 0; i < 22; i++) { // Create an empty row
    tr.appendChild(document.createElement('td'));
}
for (i = 0; i < 10; i++) { // Add 10 copies of it to the table
    table.appendChild(tr.cloneNode(true));
}
cells = table.getElementsByTagName('td'); // get all of the cells
for (i = 0; i < 220; i++) {               // number them
    cells[i].innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);

      

And the third option : add cells in one loop, creating a new row every 22 cells.

var table = document.createElement('table'), tr, td, i;
for (i = 0; i < 220; i++) { 
    if (i % 22 == 0) { // every 22nd cell (including the first)
        tr = table.appendChild(document.createElement('tr')); // add a new row
    }
    td = tr.appendChild(document.createElement('td'));
    td.innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);

      

+6


source


There are many ways to do this, but I find it helpful to create fragment

and then add everything to it. It is fast and constrains the DOM to re-paint / re-stream from a loop.

Take a look at jsbin example .

Here's the modified code:



function newNode(node, text, styles) {
  node.innerHTML = text;
  node.className = styles;
  return node;
}

var fragment = document.createDocumentFragment(),
  container = document.getElementById("container");

for(var i = 1; i <= 10; i++) {
  var tr = document.createElement("tr");
  var td = newNode(document.createElement("td"), i, "cell");
  tr.appendChild(td);
  fragment.appendChild(tr);
}

container.appendChild(fragment);

      

You can change whatever you want inside the loop, but that should start.

+1


source


This is because the DOM magically wraps the element <tbody>

around the rows of rows in the table as it is meant to be executed . Fortunately, you can rewrite your loop to add all of these table rows at the same time, rather than one at a time.

The simplest solution for this would be to store the string variable and concatenate your strings. Then, after you have concatenated your rows into one row, you can set innerHTML

your table element to one row like this:

<script>
(function() {
    var rows = '';
    for( var i = 0; i <= 10; i++ )
    {
        rows += '<tr id = "row' + i + '"><td>...</td></tr>';
    }
    document.getElementById( 'table' ).innerHTML = rows;
}());
</script>

      

Here's a JSFiddle that demonstrates what I just wrote. If you inspect the HTML with your browser developer tools, you will notice that one (and only one) tbody

wraps all of your table rows.

Also, in case you're wondering, the odd function that wraps around this code is just a fancy way of keeping the variables you've created from the global (because they don't need it). See this blog post for more details on how this works.

0


source







All Articles