Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
How to solve Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at printTime when trying to show current time with JS and html

error

function printTime() {
  let clock = document.getElementById("clock"); // use dom to choose a place for the clock
  let curr = new Date();
  let currtime =
    curr.getFullYear() + "/" + (curr.getMonth() + 1) + "/" + curr.getDate();
  clock.innerHTML = currtime;
  setTimeout("printTime()", 1000);
}

window.onload = function () {
  printTime();
};

It seems like the time displays correctly but I am curious why am I getting this error: lab6.js:6 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at printTime

when I also added <div id="clock"></div>in the HTML code?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think your code is working fine here

function printTime() {
  let clock = document.getElementById("clock"); // use dom to choose a place for the clock
  let curr = new Date();
  let currtime =
    curr.getFullYear() + "/" + (curr.getMonth() + 1) + "/" + curr.getDate();
  clock.innerHTML = currtime;
  setTimeout("printTime()", 1000);
}

window.onload = function () {
  printTime();
};
<div id="clock"></div>

about 4 years ago · Juan Pablo Isaza Report

0

In my opinion you get the error because the element is not yet rendered on the window.onload . Instead you should be looking for body.onload , or in other words, if you would set the call to printTime directly in the body tag, it would work fine.

<body onload="printTime()">

In any case, wrapping the printTime() inside an arrow function also works without the error :

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
    <script>
      function printTime() {
        let clock = document.getElementById("clock"); // use dom to choose a place for the clock
        let curr = new Date();
        let currtime = curr.getFullYear() + "/" + (curr.getMonth() + 1) + "/" + curr.getDate();
        clock.innerHTML = currtime;
        setTimeout("printTime()", 1000);
      }

      window.onload = () => {
        printTime();
      };
    </script>
  </head>
  <body>
    <div id="clock"></div>
  </body>
</html>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!