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?

3
  • Try using document.querySelectorAll(".ClsAnschrift"); Commented Dec 15, 2020 at 7:02
  • Try var arAddresses = document.querySelectorAll(".ClsAnschrift"); instead Commented Dec 15, 2020 at 7:03
  • This may help: stackoverflow.com/questions/3871547/… Commented Dec 15, 2020 at 7:05

5 Answers 5

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>

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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));

Comments

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.

Comments

0

Try this:

Array.from(arAddresses).forEach(element => console.log(element.innerHTML));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.