0

I have a little problem that has been hard to solve, harder than I believed. I assume there will be a simple answer to this one.

So, I have made a timer using javascript, the timer works fine and that's not a problem. However, I am using this to define the timer:

document.getElementById("timerz").innerHTML = 0;

And then using this to display the timer

<span id=timerz></span>

I know that I can't use an element with the same ID on multiple places. However, I've tried this:

document.getElementsByClass("timerz").innerHTML = 0;

And then

<span class=timerz></span>

And it is still not working, how can I solve this? It's very strange.

Jax Flaxx
  • 57
  • 5

3 Answers3

0

use getElementsByClass with s

 document.getElementsByClassName("timerz")[0].innerHTML = 0;

or

var timerz = document.getElementsByClassName("timerz");
var i;
for (i = 0; i < timerz.length; i++) {
    timerz[i].innerHTML = 0;
}
0

So here you need to understand how javascript works.

document.getElementsByClassName("timerz")

This will return an array of spans as we have used a same class for each span. Now we need to iterate each element and than put html inside it.

I recommed you to go through any javascript tutorial

var spans = document.getElementsByClassName("timerz")
for(span of spans){
 span.innerHTML = "0"
}
<span class="timerz"> </span>
<span class="timerz"> </span>
<span class="timerz"> </span>
<span class="timerz"> </span>
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
0

This is how you iterate over a NodeCollection (which returns whenever you use any query method that potentially can return more than one element like document.querySelectorAll, document.getElementsByClassName, document.getElementsByTagName):

var timerz = document.getElementsByClassName("timerz");

Array.prototype.forEach.call(timerz, function(timer, index) {
    timer.textContent = `This is the timer with the index ${index}.`
})
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>

You have to use Array.prototype.forEach.call here because the data type returned by document.getElementsByClassName, despite being very similar to an Array, is not an actual Array. In some browsers NodeCollection may not have a method forEach().

Another option is to create an actual Array from the NodeCollection:

var timerz = Array.from(document.getElementsByClassName("timerz"));

timerz.forEach(function(timer, index) {
    timer.textContent = `This is the timer with the index ${index}.`
})
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
<div class="timerz"></div>
connexo
  • 53,704
  • 14
  • 91
  • 128