0

JS sends current time (hh:mm) and updates HTML page using .innerHTML.

I want to display time at two locations in same page so I duplicated the html

    <div class="time"></div>
    <div class="time"></div>

now using [0] and [1], I can call the same class twice.

    document.getElementsByClassName("time")[0].innerHTML = hour+":"+minute+":"+second;
    document.getElementsByClassName("time")[1].innerHTML = hour+":"+minute+":"+second;

Is there anyway I can call both by single line. Did a quick search but couln't find solution.

Ashesh Shrestha
  • 328
  • 4
  • 15

3 Answers3

1

Using querySelectorAll:

// Not your time format, but still used to visualize
const date = new Date();

document.querySelectorAll('.time').forEach(elem => elem.innerText = date);
<div class="time"></div>
<div class="time"></div>

Using getElementsByClassName:

// Again to visualize
const date = new Date();

Array.from(document.getElementsByClassName('time')).forEach(elem => elem.innerText = date);
<div class="time"></div>
<div class="time"></div>

This works too (Spread syntax):

const date = new Date();

[...document.getElementsByClassName('time')].forEach(elem => elem.innerText = date);
<div class="time"></div>
<div class="time"></div>
CodeF0x
  • 2,624
  • 6
  • 17
  • 28
0

You can perform a Array.from and forEach ( ES6 )

Array.from(document.getElementsByClassName("time")).forEach(function(item) {
   item.innerHTML = hour+":"+minute+":"+second;
});

If you must manipulate DOM frequently maybe i suggest you to use Jquery for an easier way to perform this kind of thing

Aswell if you want to learn more about loop for HTML collection , this topic is a must seen

Loic H
  • 328
  • 4
  • 12
0

To get the index, pass as second parameter:

document.querySelectorAll(".time").forEach((el,i)=>el.innerHTML="element " + i)//hour+":"+minute+":"+second;)
   
<div class="time"></div>
 <div class="time"></div>