How to use a class selector instead of the id "clock" for the counter to work in multiple instances (Divs)?

Asked

Viewed 21 times

0

getElementsByClassName() did not work.

document.addEventListener('DOMContentLoaded', timerOffer);
function timerOffer() {
       // Set the date we're counting down to
        var countDownDate = new Date("12 31, 2020 20:00:00").getTime();
        
        // Update the count down every 1 second
        var x = setInterval(function() {
        
          // Get today's date and time
          var now = new Date().getTime();
            
          // Find the distance between now and the count down date
          var distance = countDownDate - now;
            
          // Time calculations for days, hours, minutes and seconds
          var days = Math.floor(distance / (1000 * 60 * 60 * 24));
          var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          var seconds = Math.floor((distance % (1000 * 60)) / 1000);
            
             // Formata o número menor que dez, ex: 08, 07, ...
                if (hours < 10) {
                    hours = "0" + hours;
                    hours = hours.substr(0, 2);
                }
                if (minutes < 10) {
                    minutes = "0" + minutes;
                    minutes = minutes.substr(0, 2);
                }
                if (seconds <= 9) {
                    seconds = "0" + seconds;
                }
          // Output the result in an element with id="demo"
           document.getElementById("clock").innerHTML = days + " :" + hours + " :"
          + minutes + " :" + seconds;
          
         
                
          // If the count down is over, write some text 
          if (distance < 0) {
            clearInterval(x);
            document.getElementById("clock").innerHTML = "ESGOTADO";
          }
        }, 1000);
}

2 answers

0

Good, I particularly recommend using the method querySelector(), then to select all class elements "clock", you’d call her from inside the document as:

document.querySelector(".clock"); // usando inclusive o mesmo formato processado em CSS

0

// Output the result in an element with id="demo"
        document.querySelectorAll(".clock").forEach(function(clock, index) {
            clock.innerHTML = days + " :" + hours + " :" + minutes + " :" + seconds;
        });


        // If the count down is over, write some text 
        if (distance < 0) {
            clearInterval(x);
            document.querySelectorAll(".clock").forEach(function(clock, index) {
                clock.innerHTML = "ESGOTADO";
            });

<!-- begin snippet: js hide: false console: true babel: false -->

Browser other questions tagged

You are not signed in. Login or sign up in order to post.