0

I have the following code:

var arAddresses = document.getElementsByClassName("ClsAnschrift");
arAddresses.forEach(element => console.log(element.innerHTML));

and I get the following error: Uncaught TypeError: arAddresses.forEach is not a function What is the Problem?

Ashish
  • 6,791
  • 3
  • 26
  • 48
Max Lindner
  • 171
  • 1
  • 1
  • 7

5 Answers5

1

use Document.querySelectorAll()

var arAddresses = document.querySelectorAll(".ClsAnschrift");
arAddresses.forEach(element => console.log(element.innerHTML));
<div class="ClsAnschrift">1</div>
<div class="ClsAnschrift">2</div>
<div class="ClsAnschrift">3</div>

The problem with Document.getElementsByClassName() is (as stated in the docs)

The getElementsByClassName method of Document interface returns an array-like object of all child elements...

array like objects have no forEach functionality

caramba
  • 21,963
  • 19
  • 86
  • 127
1

The reason its not working because when you try to select elements using document.getElementsByClassName, it returns HTMLCollection not an array, so you need to convert it into Array first and then apply forEach on it.

Convert into array using: Array.from(variable)

Use it this way:

var arAddresses = document.getElementsByClassName("ClsAnschrift");
Array.from(arAddresses).forEach(element => console.log(element.innerHTML));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Prathamesh Koshti
  • 1,322
  • 10
  • 17
1

HTMLCollection does not work with foreach, you can use "for ... of" instead.

var list = document.getElementsByClassName("ClsAnschrift");
for (const element of list) {
  console.log(element.innerHTML)
}
<div class="ClsAnschrift">a</div>
<div class="ClsAnschrift">b</div>
Jannchie
  • 690
  • 6
  • 18
0

Because arAddresses is a HTMLCollection. Browsers doesn't support using forEach on HTMLCollection. You can use for loop to iterate over nodeList or you can make array from the nodeList and then use forEach.

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
0

Try this:

Array.from(arAddresses).forEach(element => console.log(element.innerHTML));
Jack Kuo
  • 43
  • 5