You can fix this by running the script when the window has loaded:
addEventListener('load', function() {
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 22) {
document.getElementById("cielo").setAttribute("class", "giorno");
} else {
document.getElementById("cielo").setAttribute("class", "notte");
}
});
that way, the elements you want to select have been created on the page. If you run it outside a load
event listener, the script will try to find the element with id="cielo"
before it is created in the JavaScript DOM.
The reason why this works in jsfiddle is because jsfiddle automatically adds this to any scripts running. To disable that, go to the sidebar on the left, and in the dropdown that says onLoad
now, select No wrap - in <head>
.