Hi all, I just started learning JavaScript earlier this week and I wanted to apply some of the things I’ve learned by creating a calendar based from this tutorial and applying some functionality to it.
However, I am having an issue where unordered list items are not being displayed properly when created by JavaScript. If I manually enter the list items in the HTML the list items appear as they should. The list items in question are the days of the month.
Here is what the calendar should look like -
In the above screenshot I manually entered the days 1-31 in an unordered list just as the tutorial does. Notice the day numbers line up perfectly with the days of the week.
Here is what my calendar looks like when the list items are generated by a JavaScript loop -
(New users are only allowed one image? See my reply for this image… I guess).
In the above screenshot the days are not lined up properly.
I would like to generate the days using JavaScript so that when a user selects a month at the top, the correct amount of days for that month are created and appended to the list. Below are the pieces of code I’ve written to test this functionality.
HTML
<ul class="weekdays">
<li>Su</li>
<li>Mo</li>
<li>Tu</li>
<li>We</li>
<li>Th</li>
<li>Fr</li>
<li>Sa</li>
</ul>
<ul class="days" id="listDays"></ul>
<script src="script.js"></script>
CSS
.weekdays {
margin: 0px;
padding: 10px 0;
background-color: #ddd;
}
.weekdays li {
display: inline-block;
width: 13.6%;
text-align: center;
color: #666;
}
.days {
margin: 0px;
padding: 10px 0;
background-color: #eee;
}
.days li {
display: inline-block;
width: 13.6%;
text-align: center;
margin-bottom: 5px;
font-size: 12px;
color: #777;
}
JavaScript
let monthLength = 31;
let listDays = document.getElementById('listDays');
for (var i = 1; i <= monthLength; i++) {
let listItem = document.createElement('li');
listItem.textContent = i;
listDays.appendChild(listItem);
}
I still have a lot of code to write but for now I created a variable named monthLength and gave it a value of 31 days for testing purposes. Please help