Sander
Sander

Reputation: 558

Update a HTML tag after an interval

I am trying to make an HTML5 clock as my first project, but I am having problems with updating the .innerHTML property every second, though console.log works just fine. Here is my main.js:

     var baseDate = new Date();
    var seconds =   baseDate.getSeconds();
    var secondsElement = document.getElementsByClassName("seconds");

 setInterval(function() {secondsElement.innerHTML = seconds;
        console.log(seconds);}, 1000);

I also checked everything for typos regarding class names, but found nothing.

Upvotes: 0

Views: 901

Answers (1)

adeneo
adeneo

Reputation: 318182

You're writing the same time every time. You need to update the time inside the interval, otherwise the variable will never change :

setInterval(function() {
    var baseDate       = new Date(),
        seconds        = baseDate.getSeconds(),
        secondsElement = document.getElementsByClassName("seconds")[0];
    secondsElement.innerHTML = seconds;
}, 1000);

FIDDLE

Upvotes: 1

Related Questions