JavaScript JavaScript and the DOM Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

Vijayalaxmi vastrad
Vijayalaxmi vastrad
2,781 Points

Uncaught TypeError: Cannot set property 'innerHTML' of null

//html <div class="time">last time: <div class="date" style="display:inline-block; margin-right:.7rem;"> <span id="date"></span> <span id="month"></span> <span id="year"></span> </div> <div class="time" style="display:inline-block"> <span id="hours"></span> <span id="minutes"></span> <span id="seconds"></span> </div> </div> ///js window.onload= function(){ clock();

function clock() {
    const fullDate = new Date();
    var day = fullDate.getDate();
    var month = fullDate.getMonth();
    var year = fullDate.getFullYear();
    var hour = fullDate.getHours();
    var minutes = fullDate.getMinutes();
    var sec = fullDate.getSeconds();

    if (hour < 10) {
        hour = "0" + hour;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (sec < 10) {
        sec = "0" + sec;
    }
    if (day < 10) {
        day = "0" + day;
    }
    if (month < 10) {
        month = "0" + month;
    }

    document.getElementById('date').innerHTML=day;
    document.getElementById('month').innerHTML="/" + month;
    document.getElementById('year').innerHTML = "/" + year;

    document.getElementById('hours').innerHTML = hour;
    document.getElementById('minutes').innerHTML = ":" + minutes;
    document.getElementById('seconds').innerHTML = ":" + sec;

}
setInterval(clock, 100);

}

2 Answers

Steven Parker
Steven Parker
177,536 Points

This works for me after copy and paste. Is it possible that you accidentally changed the ID of one of the HTML elements?

For example, if the first span had an ID of "dale" instead of "date" I would expect to get that error.

Also, you could use 1000 instead of 100 for the interval and get the same results with 10% of the effort.

Vijayalaxmi vastrad
Vijayalaxmi vastrad
2,781 Points

mine sometimes error occurs sometime do not. not getting why. anyway thank you so much