Vanilla JS ForEach element and assigning ascending variable

Viewed 420

I'm trying to make a simple one month calendar using Vanilla JS. I read that PHP can be used to create multiple repeating elements but I was wondering whether doing it the I'm trying is possible. I'm creating buttons and using a for loop to make 31 of them to fill up my month. I'm also trying to make it so the button contains the day number using the variable day. Not sure how to do that, I was thinking for loop and using i as the value for day, but then it would just end on whatever the last i value was.

Since it's not working I'm coming here for help, I'd like to solve this using Vanilla JS if possible. Thank you.

TLDR: For loop to make buttons and variable to assign ascending value to each.

<!DOCTYPE html>
<html>

<head>
    <title>Calendar</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript">
        var day;

        function dateMaker() {
            for (i = 0; i < 31; i++) {
                var btn = document.createElement("button");
                btn.className("date");
                btn.innerHTML = day;
                document.body.appendChild(btn);
            }
        }
    </script>
</head>

<body>
    <h1>July 2020</h1>
    <div id="calendar">
        <script>
            dateMaker();
        </script>
    </div>
</body>

</html>
1 Answers

You need to add use classList.add to add class to your dynamic elements. Couple of mistakes and fixes which i have hightlighted below

  1. Also, ideally use .textContent intead of .innerHTML
  2. You can appendChild and display you days in the calendar
  3. Use classList to add classes to your dynamic elements
  4. You are declaring day variable but not using it in your code.

Run Snippet below.

function dateMaker() {
  for (i = 1; i < 31; i++) {
    var btn = document.createElement("button");
    btn.classList.add("date");
    btn.textContent = i;
    document.getElementById('calendar').appendChild(btn) ;
  }
}
dateMaker();
<!DOCTYPE html>
<html>

<head>
  <title>Calendar</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript">
    var day;
  </script>
</head>
<body>
  <h1>July 2020</h1>
  <div id="calendar"></div>
    <script>
    </script>
  </div>
</body>

</html>

Related