Reputation: 817
Actually I'm working on a function that compares two dates (one date I get from my hidden input, another date - current datetime). I wrote a function in JS which works perfect:
var elements = document.getElementsByClassName("getTime");
var names = [];
for(var i=0; i<elements.length; i++) {
names = elements[i].value;
var dece = moment(names).format();
var cureTime = moment().format();
seco=moment().diff(dece, 'seconds');
if ((Math.floor(seco / 60)) >= 1 && (Math.floor(seco / 60))<60) {
console.log(Math.floor(seco / 60) + " minutes");
document.getElementsByClassName("time").innerHTML = Math.floor(seco / 60) + " minutes ago";
}else if(((Math.floor(seco / 3600)) >= 1) && ((Math.floor(seco / 3600))<24))
{
console.log(Math.floor(seco / 3600) + " hours");
document.getElementsByClassName("time").innerHTML = Math.floor(seco / 3600) + " hours ago";
}else if (((Math.floor(seco / 86400)) >= 1) && ((Math.floor(seco / 86400)) <30))
{
console.log(Math.floor(seco / 86400) + " days");
document.getElementsByClassName("time").innerHTML = Math.floor(seco / 86400) + " days ago";
}else if (((Math.floor(seco / 2592000)) > 1) && ((Math.floor(seco / 2592000)) <= 12))
{
console.log(Math.floor(seco / 2592000) + " months");
document.getElementsByClassName("time").innerHTML = Math.floor(seco / 2592000) + " months ago";
}else if((Math.floor(seco / 31536000)) > 1)
{
console.log(Math.floor(seco / 31536000) + " years");
document.getElementsByClassName("time").innerHTML = Math.floor(seco / 31536000) + " years ago";
}
}
As a result all of those console.logs (in each if statement) return me the right difference in dates. But now I can't understand how can I parse all of these differences into the appropriate span fields with the same class name. My HTML looks like this:
@foreach($repoData as $kek)
<span class="time" id="openedOn"></span>
<input type="hidden" class="getTime" id="time" value='{!! $kek->created_at !!}'>
@endforeach
To be clear this FOREACH generates me several dates that are stored in the hidden input. Then I get values from this hidden input and pass them to my function in JS. So I can't understand how should I parse elements from my JS function to that span with class name - "time". Please help.
Upvotes: 0
Views: 68
Reputation: 6632
getElementsByClassName
functions returns an array(Read more here) and hence you need to use array notation to access its elements
document.getElementsByClassName("time")[0].innerHTML
In your case, since your accessing the elements within a loop you should simply make use of the counter(i
).
document.getElementsByClassName("time")[i].innerHTML
Replace the above to all the conditions for it to work.
Upvotes: 1