Trouble displaying javascript in HTML

Hello guys, I’m not sure why my code isn’t working and it doesn’t print the date in the browser. Could you please help me?

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script src="src/index.js"></script>

    <script type="text/javascript">
      function myFunction() {
        var today = new Date();
        var date = today.getDay();
        var daylist = [
          "Sunday",
          "Monday",
          "Tuesday",
          "Wednesday ",
          "Thursday",
          "Friday",
          "Saturday"
        ];

        var dayOfTheWeek = daylist[date];

        document.getElementById("myText").innerHTML = dayOfTheWeek;
      }
    </script>
  </head>

  <body onload="myFunction()">
    <div id="app"></div>

    <h1>
      Today is
      <script type="text/javascript">
        document.write(dayOfTheWeek)
      </script>
    </h1>
  </body>
</html>

there is no element with such an id

<body onload="myFunction()"> is also very unusual and same goes for

<script type="text/javascript">
        document.write(dayOfTheWeek)
      </script>

I’d recommend you start with a basic JS tutorial.

https://javascript.info can also help you on how to interact with the DOM (writing from JS to HTML)

1 Like
  1. dayOfTheWeek has scope local to the function. I.e. the code which later attempts to reference it can’t see it.
  2. Even if you move dayOfTheWeek so that it has global scope, the code doesn’t work. By adding console.log() statements to the different script sections, I find that myFunction() is executed after the section which attempts to display dayOfTheWeek.

You probably need to scrap the <script> which attempts to write dayOfTheWeek and use the document.getElementById() method instead - after you create the “mytext” element it references.

But I’ve already exhausted my limited Javascript knowledge so I can’t be 100% confident.