re: How do I use .forEach on DOM Elements? VIEW POST

FULL DISCUSSION
 

I just want to make a few points.

  1. I haven't used a traditional for loop in years.
  2. Like others have mentioned, you should be using more modern functions such as querySelectorAll.
  3. getElementsByClassName returns an HTMLCollection, which is why you were getting the error. NodeLists have a forEach method and HTMLCollections do not.

My initial instinct on circumventing this is the following:

var timestamps = document.getElementsByClassName("utc-time");

[].slice.call(timestamps).forEach(function(timestamp) {
      var localTime       = updateLocalTime(timestamp.innerHTML);
      timestamp.innerHTML = localTime;
});

HTMLCollections are array-like. They are iterable and have a length property. The slice function can convert array-like objects into Arrays. this is bound to our array-like object. slice iterates over this using the length property since no other arguments were given. All the elements are returned in a new Array then we can call forEach method on our Array

But looking at your initial answer:

var timestamps = document.getElementsByClassName("utc-time");

[].forEach.call(timestamps, function(timestamp) {
      var localTime       = updateLocalTime(timestamp.innerHTML);
      timestamp.innerHTML = localTime;
});

Is a good solution too if not better. timestamps is bound to this then forEach method iterates over the array-like object by using the length property. My solution would have looped through the array-like object once then the newly created array versus this solution which is once.

code of conduct - report abuse