{ elemen" /> { elemen" /> { elemen"/>

Foreach not works on html collection

633 Views Asked by At

I have two files, one of js:

const a = document.getElementsByTagName("body")[0];

const d = a.getElementsByTagName("h1");

d.forEach(element => {
   element.innerHTML = "the text has changed";
});

and html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>David
</title>
  </head>
  <body>
    <h1>hello1</h1>
    <h2>david</h2>
    <h3>ariel</h3>
    <h4>yahav</h4>
    <h1>hello2</h1>
    <h1>hello3</h1>
    <script src="food.js"></script>
  </body>
</html>

I am trying to change the text of each h1 element to the same text, but it's not working, meaning when i run it on the broswer, all the "h1" texts remains the same.

not sure why, because "d" is an html collection, and i run on it with the foreach.

Basically everything stright forward, so not sure what i could try.

appreciate any help!

1

There are 1 best solutions below

7
Peter Konokhov On

you shouldn't use forEach because HTMLCollections don't implement a forEach method.

Use the for loop

const a = document.getElementsByTagName('body')[0]
const d = a.getElementsByTagName('h1')

for (let elem of d) {
    elem.innerHTML = 'new text'
}