Home > database >  Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?
Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?

Time:11-25

function show() {
  var now = new Date();
  var year = now.getFullYear(),
    month = now.getMonth()   1,
    date = now.getDate(),
    day = now.getDay(),
    hour = now.getHours(),
    minute = now.getMinutes(),
    second = now.getSeconds(),
    hour = check(hour);
  minute = check(minute);
  second = check(second);

  var week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday\n"];
  day = week[day];
  var t = "Today is:"   year   "year"   month   "month"   date   hour   ":"   minute   ":"   second;
  return t;
}

function check(i) {
  if (i < 0) {
    i = "o"   i;
  }
  return i;
}
var h = document.getElementById("show");
h.innerHTML = show();

var h = document.getElementById("show");
setInterval(function() {
  h.innerHTML = show();
}, 1000);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="../js/date.js"></script>
</head>

<body>

  <div id="show"></div>


</body>

</html>

I hope to display the current system time on the web page using an external link method, but I don't know why an error occurs,Is it because of code error code? i think i need help,Please help me debug the code

CodePudding user response:

You get that because you try to access your HTML element before the page has loaded. You can add the defer keyword at your html file in the script tag and it should be ok

<script src="../js/date.js" defer></script>
  • Related