Question

I found something here about that but I have a strange problem.

My code is:

var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 22) {
    document.getElementById("cielo").setAttribute("class", "giorno");
} else {
    document.getElementById("cielo").setAttribute("class", "notte");
}

It work perfectly on http://jsfiddle.net/Geimsiello/9d27v/ but if I try on my website or in local, dubugger tell me: Uncaught TypeError: Cannot call method 'setAttribute' of null

Someone that could help me? I need to change class to different divs.

Was it helpful?

Solution

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>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top