Search code examples
javascriptloopsappendcreateelement

Generate table rows in the loop with Javascript


I don't get how to generate rows after some condition in the loop. A code below tries to make calendar table, but I can't figure out why it shows only last row with condition. Please help to fix it

let start = document.querySelector('div');
let table = document.createElement('table');
let row = document.createElement('tr');
let date = new Date(2015,5);

while (date.getMonth() == 5){
  let td = document.createElement('td');
  td.innerHTML= date.getDate();
  row.appendChild(td);

  if ( date.getDay()%6 == 0){
    table.appendChild(row) //want that it add new row after each 7 days
    console.log(table)
    row.innerHTML = '';
  }

  date.setDate( date.getDate() + 1) ;   
}

table.appendChild(row)
start.appendChild(table)
table  {
  border-collapse : collapse;
  margin          : 2em 1em;
  }
td {
  padding    : .2em .8em;
  border     : 1px solid darkblue;
  }
<div class="container"></div>


Solution

  • This should do the trick,

    let start = document.querySelector('div');
    let table = document.createElement('table');
    let row = document.createElement('tr');
    let date = new Date(2015,5);
    
    while (date.getMonth() == 5){
      let td = document.createElement('td');
      td.innerHTML= date.getDate();
      row.appendChild(td);
    
      if ( (date.getDay()%7) == 0){
        table.appendChild(row) //want that it add new row after each 7 days
        row = document.createElement('tr');
      }
    
      date.setDate( date.getDate() + 1) ;   
    }
    
    table.appendChild(row)
    start.appendChild(table)
    table  {
      border-collapse : collapse;
      margin          : 2em 1em;
      }
    td {
      padding    : .2em .8em;
      border     : 1px solid darkblue;
      }
    <div class="container"></div>

    I just made two changes,

    • On line #12, modified the if condition, if (date.getDay()%6 == 0) => if (date.getDay()%7 == 0) the former would be true for both 0(Sunday) and 6(Saturday), causing incorrect number of rows. The latter correctly breaks the row by doing modulo 7 as there are 7 days in a week
    • On line #15, I replaced, row.innerHTML = ''; => row = document.createElement('tr');
      the former just mutates the reference of the row already added to the table, and thus effectively deletes the cells in the row. With the latter you are creating a new row object and adding cells to it.