{element.innerHTML="text Changed";}); There is also an html file: Can't use foreach loop on HTML collection-PHP Chinese Network Q&A
Can't use foreach loop on HTML collection
P粉930534280
P粉930534280 2023-08-29 09:48:35
0
1
446

I have two files, one is a js file:

const a = document.getElementsByTagName("body")[0]; const d = a.getElementsByTagName("h1"); d.forEach(element => { element.innerHTML = "Text changed"; });

There is also an html file:

   David  

Hello 1

David

Ariel

Yahav

Hello 2

Hello 3

I tried to change the text of each h1 element to the same text, but it didn't work, that is when I run it on the browser, all the "h1" text still remains the same.

Not sure why, since "d" is a html collection and I use foreach to run on it.

Basically everything is pretty simple so not sure what I can try.

Thanks for any help!

P粉930534280
P粉930534280

reply all (1)
P粉864594965

You should not useforEachbecause HTMLCollections does not implement the forEach method.

Use for loop

const a = document.getElementsByTagName('body')[0] const d = a.getElementsByTagName('h1') for (let elem of d) { elem.innerHTML = '新文本' }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!