Reputation: 388
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.
Upvotes: 0
Views: 412
Reputation: 379
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>
Upvotes: 0
Reputation: 2682
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>
Upvotes: 1
Reputation: 348
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
Upvotes: 0