0

I have attempted using the for loop to display my Countdown, but I don't know where I am getting it wrong. Is there a simpler way to display the countdown for each row using vanilla javascript?

My Table Below:

<html>
<body> 
<table style="width:50%" id= "tab">
    <tr>
<th>Name</th>
<th>Exp</th>
<th>Count Down</th>
</tr>
    <tr>
     <td> A</td>
     <td class = 'exp1'> 09/08/2019</td>
     <td class = 'demo'> </td>   
    </tr>
    <tr>
     <td> B</td>
     <td class = 'exp1'> 09/08/2020</td>
     <td class = 'demo'> </td>   
    </tr>
</table>
</body>
</html>

Below is my javascript code:

<script>
var exp = document.getElementById('tab').getElementsByClassName('exp1');

var x = document.getElementById('tab').getElementsByClassName('demo');

var   now = new Date();
function test(){

for (i = 0; i<exp.length; i++){
var  e = new Date( exp[i].innerHTML);
var  timeDiff = e.getTime() - now.getTime();
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours   = Math.floor(minutes / 60);
var days    = Math.floor(hours   / 24);
hours %=24;
minutes %=60;
seconds %=60;
var timer = setTimeout('test()', 1000);   
}

for (i=0; i<x.length; i++){
x[i].innerHTML = days  + " " +  hours + " " + minutes + " " + seconds;
}
}

</script>
  • Possible duplicate of [How do I loop through children objects in javascript?](https://stackoverflow.com/questions/17094230/how-do-i-loop-through-children-objects-in-javascript) – Alexander Holman Oct 08 '18 at 14:23

1 Answers1

0

First, you should give your a class property instead of an id as there should be only one element with the same id.

Second, you can get all elements with

var elements = document.getElementsByClassName('demo')

Third, you can then do

var c;
for (c = 0; c < elements.length; c++) {
// calculate and change the value here
// for each elements[c]
}

For further explanation see: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp


Edit as answer to comment:

You can call the function every second with

window.setInterval(function(){
/// call your function here
}, 1000);

See What's the easiest way to call a function every 5 seconds in jQuery?

On how to calculate the time from the timediff see Check time difference in Javascript

To change the value inside of the you add the following inside your for loop

document.getElementsByClassName('demo')[c].innerHTML = newstring

as already answered here: Setting innerHTML: Why won't it update the DOM?

State
  • 3
  • 4