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?
CodePudding user response:
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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>