How do I use the same id more than once with getElementById()?

Asked

Viewed 528 times

4

Hey, guys. All right?

I have a chronometer that is in javascript and I want it to appear more than once on a specific page.

The problem is that it works only the first time it appears on the page.

I imagine it’s because of the ids that are duplicated on the html page (id="days" id="hours" id="minutes" id="Seconds") when I try to duplicate the second stopwatch. But if I want to call the timers I need to use these ids.

To try to get around the problem I tried using getElementsByClassName() instead of getElementById(). So I could use classes instead of ids in my HTML. So, I could call the javascript code through the class more than once, no problem. However, my code did not work with getElementsByClassName(). The timer simply does not appear when I try to use this function.

Does anyone have any solution for this stopwatch to work more than once on the same page?

var today = new Date();
var dd = String(today.getDate() + 1).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + ' ' + dd + ', ' + yyyy;
const second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;

let countDown = new Date(today).getTime(),
    x = setInterval(function() {

      let now = new Date().getTime(),
          distance = countDown - now;

      document.getElementById('days').innerText = Math.floor(distance / (day)),
        document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
        document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
        document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second);
      
    }, second)
<div class="conteiner-countdown-loop">
  <ul>
    <li class="countdown-loop"><span id="days"></span>dias</li>
    <li class="countdown-loop"><span id="hours"></span>Horas</li>
    <li class="countdown-loop"><span id="minutes"></span>Minutos</li>
    <li class="countdown-loop"><span id="seconds"></span>Segundos</li>
  </ul>
</div>

  • Hello, Bacco. All right? For some reason, this code stopped working from yesterday to today. I tried to understand the problem but could not. I suppose it is in the function that gets today’s date. Could you give me a light? I thank you for your attention.

1 answer

8


Solutions have many, but with the JS you are using, the ID is required
(but has an alternative with class in the end).

You can number the Ids:

<li class="countdown-loop"><span id="days1"></span> Dias</li>
...
<li class="countdown-loop"><span id="days2"></span> Dias</li>
...
<li class="countdown-loop"><span id="days3"></span> Dias</li>
...

And when updating, use a loop:

for (var i = 1; i <= 3; i++ ) {
  document.getElementById('days' + i).innerText = Math.floor(distance / (day)),
  //                             ^-- note a concatenação
  ...

Probably you will use different times in each stopwatch, then you just change the time reference in each loop iteration, whether with an array or any other technique, but this escapes the question problem, which was solved with the loop. Programming, after all, is this, figuring out how to use language resources to solve the task.


Demonstration:

var today = new Date();
var dd = String(today.getDate() + 1).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + ' ' + dd + ', ' + yyyy;
const second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;

let countDown = new Date(today).getTime(),
    x = setInterval(function() {

      let now = new Date().getTime(),
          distance = countDown - now;

      for (var i = 1; i <= 3; i++ ) {
        document.getElementById('days'+i).innerText = Math.floor(distance / (day)),
        document.getElementById('hours'+i).innerText = Math.floor((distance % (day)) / (hour)),
        document.getElementById('minutes'+i).innerText = Math.floor((distance % (hour)) / (minute)),
        document.getElementById('seconds'+i).innerText = Math.floor((distance % (minute)) / second);
      }
    }, second)
<div class="conteiner-countdown-loop">
  <ul>
    <li class="countdown-loop"><span id="days1"></span> Dias</li>
    <li class="countdown-loop"><span id="hours1"></span> Horas</li>
    <li class="countdown-loop"><span id="minutes1"></span> Minutos</li>
    <li class="countdown-loop"><span id="seconds1"></span> Segundos</li>
  </ul>
  <ul>
    <li class="countdown-loop"><span id="days2"></span> Dias</li>
    <li class="countdown-loop"><span id="hours2"></span> Horas</li>
    <li class="countdown-loop"><span id="minutes2"></span> Minutos</li>
    <li class="countdown-loop"><span id="seconds2"></span> Segundos</li>
  </ul>
  <ul>
    <li class="countdown-loop"><span id="days3"></span> Dias</li>
    <li class="countdown-loop"><span id="hours3"></span> Horas</li>
    <li class="countdown-loop"><span id="minutes3"></span> Minutos</li>
    <li class="countdown-loop"><span id="seconds3"></span> Segundos</li>
  </ul>
</div>


If the timers are the same, you can use class:

Note that the getElementsByClassName returns multiple elements, you need to iterate on them.

var today = new Date();
var dd = String(today.getDate() + 1).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + ' ' + dd + ', ' + yyyy;
const second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;

let countDown = new Date(today).getTime(),
    x = setInterval(function() {
      let now = new Date().getTime(),
          distance = countDown - now,
          spanSeconds = document.getElementsByClassName('seconds'),
          i = spanSeconds.length,
          valueSeconds = Math.floor((distance % (minute)) / second);
  
      while(i--) spanSeconds[i].innerText = valueSeconds;
    }, second)
<div class="conteiner-countdown-loop">
  <ul>
    <li class="countdown-loop"><span class="seconds"></span> Segundos</li>
  </ul>
  <ul>
    <li class="countdown-loop"><span class="seconds"></span> Segundos</li>
  </ul>
  <ul>
    <li class="countdown-loop"><span class="seconds"></span> Segundos</li>
  </ul>
</div>

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

  • Thanks for the answer, Bacco. I never thought about putting a counter to increment to ids in javascript code. It worked very well, but it solves part of the problem because the HTML code ids are not variable. I wouldn’t actually use different times. The timers are the same. They only repeat on the page.

  • But here I thought I could create a php function that increments a value i to the HTML id. Like you did in javascript. I just don’t know how the i value of html will be exactly equal to the i value of javascript. Would this be a good way. If so, I’ll figure out how to do it. As soon as I’m ready I’ll put it here.

  • Just generate JS with the same PHP that generates HTML - I suggest not to post together, because you asked a question of a JS problem, PHP is mere implementation and will only add noise (other visitors can get to this same question without necessarily being a project in PHP).

  • I added an example with class, since they are equal

  • 1

    The classy example worked perfectly. I was using the classy function very wrong. Thank you so much for your attention, Bacco. Have a great week!

Browser other questions tagged

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