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>
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,
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 weekrow.innerHTML = '';
=> row = document.createElement('tr');