shou2017.com
JP

JavaScript: Using the forEach Method with Objects

Sun Jun 16, 2019
Sat Aug 10, 2024

When you want to get all anchor tags included in a page and display a list of their link destinations:

Using a For Loop:

var list = document.getElementsByTagName('a');
for (var i = 0, len = list.length; i < len; i++) {
  console.log(list.item(i).href);
}

The forEach method only executes once for each element of an array, so if you write like this, you’ll get an error: Uncaught TypeError: list.forEach is not a function at.

const list = document.getElementsByTagName('a');
list.forEach(function(list)) {
    console.log(list)
}

So, to use the forEach method with objects rather than arrays, use the Object.keys() method:

const list = document.getElementsByTagName('a');
Object.keys(list).forEach(function (k) {
  console.log(list[k].href);
})
See Also