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:

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:

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

Adjust color scheme of drop-down menu

Having trouble changing the background color for my drop down menu. I tried to change the color for the sub div but it's not working. Can anyone help me fix this issue? Here is the code snippet: http://jsfiddle.net/3VBQ6/4/ #nav li:hover ul.sub li { ...

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Issues with utilizing Fetch API and JSON Data

I'm encountering some difficulties while trying to interact with my json file. I am using the fetch API to retrieve my json file but, unfortunately, when I log the response to the console, I don't see any data returned. Instead, what appears is a ...

Having issues with my jQuery getJSON request. It's returning an empty response even though

I have been struggling to find a solution to this particular issue with no luck... Here is the jQuery getJSON request that I am working on: $.getJSON("http://localhost:8080/context/json/removeEntity.html", { contentId : 1, entIndex : entityIndex ...

Transfer information from session to vue-component

Within my routes file, I obtain the current user from the session and then render the profile HTML: app.get('/profile', isLoggedIn, function(req, res) { res.render('profile.html', { user : req.user // extract user ...

When trying to access data within objects using JSON iteration, it may lead to encountering an issue of reading a

Attempting to retrieve specific data from a JSON file obtained from a website has proven challenging. While iterating through the collection of objects, undefined values are constantly encountered. Unfortunately, if the JSON is poorly structured, modificat ...

"Pair of forms and buttons to enhance user experience with Bootstrap and

Experiencing an issue with my webpage that is built using HTML, Bootstrap, and PHP. The page contains two forms: a contact form and a distribution form within a modal. The problem lies within the distribution form as clicking the button only submits the ...

The jQuery dynamic fields vanish mysteriously after being validated

I am facing an issue with my jQuery and validation. Below is the code snippet causing the problem: var fielddd = 1; $(document).on('click', '.btn.add-field', function() { fielddd++; $('#newfield').append('< ...

Utilize Javascript to trigger AJAX refreshes only when necessary

I have developed a web application that displays data fetched from an AJAX request to a PHP script on the same server. This particular application involves playing music from Spotify, and in order to ensure the displayed information is always up-to-date ...

"Classes can be successfully imported in a console environment, however, they encounter issues when

Running main.js in the console using node works perfectly fine for me. However, when I attempt to run it through a browser by implementing an HTML file, I do not see anything printed to the console. Interestingly, if I remove any mentions of Vector.ts fro ...

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

What's causing my text to slowly appear while my HTML canvas remains static and unchanged?

Can someone take a look at my code: http://jsfiddle.net/7y9Gp/2/ I've been struggling with trying to fade in and out text or images, but for some reason, my canvas object refuses to cooperate. I've tried swapping the position of the canvas with ...

Bring back object categories when pressing the previous button on Firefox

When working with a form, I start off with an input element that has the "unfilled" class. As the user fills out the form, I use dynamic code to remove this class. After the form is submitted, there is a redirect to another page. If I click the "back" ...

Refresh a javascript file using the power of jquery

I have created a PHP file that displays a session meter in Joomla's frontend using JavaScript. Additionally, I have another PHP file that shows user details and reloads using jQuery. My goal is to make the JavaScript session meter also reload when the ...

How can I indicate to the browser that the HTML page should be accessed through SSL?

I've set up a certificate on my website. Now, I only want one specific page to be accessed through SSL. Do I need to add any markup on the page itself, or is there another setting elsewhere that I should use? ...

Transferring Information from Vue to PHP: What You Need to Know

I need assistance with passing data from Vue to PHP. Currently, I receive a JSON object through a PHP query that looks like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded, ...

Implement a logging system to track and record data from both incoming requests and outgoing responses on a server powered by Express and Node.js

Is there a way for my server to log the response and request data when posting to another server? Thank you. const request = require('request'); postToIotPlatform = function postToIotPlatform(req, res, next) { var formData = JSON.stringify( ...

Prevent JavaScript from being entered into the form

I'm currently developing an "HTML editor" for one of my webpages. Right now, I want to ensure that the editor only allows input of HTML and CSS elements without any Javascript (or Jquery). I've been attempting to prevent the use of <script> ...

Can Masonry.js content be perfectly centered?

I am currently experimenting with creating a layout consisting of one to four variable columns per page using the Masonry plugin. I have been impressed with how it functions so far. However, there is an aggravating gap that persists despite my best effort ...