What is the best way to set the value of the days in a month to a div

I've been experimenting with creating a calendar using javascript, HTML, and CSS on my own. I managed to achieve some functionality like obtaining the current month and year as well as the previous month and year by clicking a button in HTML. However, I'm facing a challenge when it comes to displaying the days in the correct format. Despite referring to resources from w3schools and Google, I still feel like there are gaps in my knowledge.

My goal is to showcase the days in a div/grid structure that I have set up in HTML using CSS styling.

I understand this may seem like a basic question compared to others related to jQuery, but I'm specifically seeking a Javascript solution for learning purposes.

Here's the code snippet I tried:

<div id="caldays"></div>

JAVASCRIPT:

  let days="";
    for (let i = 1; i <= 31; i++) {
        days = days +  i;
        caldays.innerHTML = days;
        
    }

The result can be viewed here: https://i.sstatic.net/7ESQa.png

Another variation of Javascript code using div elements:

 let days="";
    for (let i = 1; i <= 31; i++) {
        days = days +  "<div> $[i] </div>";
        caldays.innerHTML = days;
        
    }

The result of this version can be seen here: https://i.sstatic.net/lygqo.png

If you could provide insight into what I might be missing or doing incorrectly, and how to rectify it, I would greatly appreciate it.

Thank you in advance to all the experts for your help and guidance. Also, please note that I have been exploring the following link for learning: https://medium.com/@nitinpatel_20236/challenge-of-building-a-calendar-with-pure-javascript-a86f1303267d but prefer using divs over tables or rows.

Answer №1

  1. Replace "double-quotes with backticks (``) in template literals.

  2. Use { } curly braces instead of [ ] square brackets.

let days = "";
for (let i = 1; i <= 31; i++) {
  days = days + `<div> ${i} </div>`;
  caldays.innerHTML = days;
}
<div id="caldays"></div>


You can also directly assign <div> ${i} </div> to innerHTML. Moreover, when there's only one line of code inside a block, you can skip the { } curly braces. For example:

for (let i = 1; i <= 31; i++) caldays.innerHTML += `<div> ${i} </div>`;
<div id="caldays"></div>




Helpful resources:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

developing a deferred commitment by utilizing promise objects

Hi everyone, I've encountered an issue with a JavaScript promise question that's throwing errors function delay(n) { return new Promise((resolve) => setTimeout(resolve, n*1000)); } The expected output should be "It is now 2 seconds later" ...

Stop the page from scrolling

I'm trying to find a way to disable page scrolling, so I used this style for the body: overflow: hidden; Surprisingly, it worked perfectly on desktop but had no effect on mobile devices. After checking out this resource, it seems that creating a ch ...

Struggling to bring in { useActionState } from 'react' while trying to follow the latest next.js tutorial with next.js v15.0.0-canary.28, react v19.0.0-rc, and types/react v18.2.21

Currently, I am following the tutorial on next.js available at https://nextjs.org/learn/dashboard-app I have reached chapter 14, which focuses on enhancing accessibility, located at https://nextjs.org/learn/dashboard-app/improving-accessibility During on ...

Troubleshooting Ajax contact form's failure to refresh (PHP and Bootstrap 4)

I have successfully implemented this code on one website, but it is not working as expected on another website. It sends the email but refreshes the page and redirects to a contact.php page with a message. Despite double-checking everything, including cha ...

Bars of varying heights (Google Chart)

I have incorporated a Google chart within a mat-grid-tile. In this setup, one column displays a value of 50, while the other showcases a value of 30. These particular values are sourced from myService and are accurate. Although when I hover over the bars i ...

Retrieving data from an HTML input tag and storing it in a variable

I'm currently working on a project that involves reading the contents of an uploaded file through an input tag and storing it in a variable. My goal is to then use an algorithm to decrypt the .txt file: <input type="button" value="decrypt" id="dec ...

Unable to utilize a function within a mongoose schema

I encountered an issue while attempting to access the schema methods of a mongoose schema in TypeScript. Schema const userSchema: Schema<IUser> = new Schema( { name: { type: String, required: [true, "Name is required"], ...

Identifying the absence of a character at the end of the last line in Node.js to detect

Currently, I am processing data line by line from a buffer. Within the buffer, the data is structured as follows: name,email,phn test1,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47332234337607223f262a372b226924282a">[em ...

Issue with JQuery Ajax button functionality

I am brand new to navigating the world of writing ajax and using a restful api...so please bear with me. On the backend, I have a Laravel 5.2 RESTful API that I'm working with, and my current task involves loading a list of categories using Jquery / ...

What sets response.setHeader apart from response.writeHead?

When it comes to sending a JSON response from my Nodejs server in my application, I have discovered two different methods. However, I am unsure about the distinctions between them. The first method involves var json = JSON.stringify(result.rows); respons ...

Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error. https://i.sstatic.net/0Liqi.jpg I have designed a visually appealing travel landing pag ...

When the C# method is executed, jQuery is reset

One feature I have on my website is a "newsletter" widget that expands when the user clicks a button. Inside the expanded section, there is an input box for email address and a submit button. The code behind this functionality verifies the email format and ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

Guide on deleting an item from an object array in AngularJS

I have an array of objects and need to delete a specific object from it: var objectArray = [{"id":"John Doe","label":"John Doe","shape":"image","image":"app/data/img/user_icon.png","color":{"background":"#db630d","border":"#7c3400"},"level":0},{"id":"Java ...

When ALIGN-ITEMS: CENTER is removed, the <a> element expands to fill the entire line

Currently, I am delving into the world of CSS and grappling with a particular behavior that has caught my attention. section{ display: flex; flex-direction: column; align-items: center; } .banner-area a.banner-btn{ padding: 15px 35px; backgrou ...

Concentrate on the disappeared div element following the AJAX request

Encountering an unusual issue here that has me a bit puzzled. In one of my DIV elements, I have included several links which trigger an AJAX call (using jQuery) upon being clicked. The server (Controller) then responds with HTML content, specifically a JS ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

AngularJS: The power of dynamic HTTP POST parameter names

Utilizing an API to update profile information allows for the addition of a nickname, email, phone number, or password in the request parameters, which will then be updated in the database. When updating a specific field, such as Nickname: { "nickname": ...

Customizing and adjusting the CSS for all individuals accessing the website

I am in the process of developing a system that will notify users in the office when a specific individual is busy and cannot answer the phone. How can I implement a feature where clicking "engaged" changes the color of the availability box to red on thei ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...