Home  >  Q&A  >  body text

Can't use foreach loop on HTML collection

<p>I have two files, one is a js file:</p> <pre class="brush:php;toolbar:false;">const a = document.getElementsByTagName("body")[0]; const d = a.getElementsByTagName("h1"); d.forEach(element => { element.innerHTML = "Text changed"; });</pre> <p>There is also an html file: </p> <pre class="brush:php;toolbar:false;"><!DOCTYPE html> <html lang="en"> <head> <title>David </title> </head> <body> <h1>Hello 1</h1> <h2>David</h2> <h3>Ariel</h3> <h4>Yahav</h4> <h1>Hello 2</h1> <h1>Hello 3</h1> <script src="food.js"></script> </body> </html></pre> <p>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. </p> <p>Not sure why, since "d" is a html collection and I use foreach to run on it. </p> <p>Basically everything is pretty simple so not sure what I can try. </p> <p>Thanks for any help! </p>
P粉930534280P粉930534280417 days ago481

reply all(1)I'll reply

  • P粉864594965

    P粉8645949652023-08-30 00:31:40

    You should not use forEach because 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 = '新文本'
    }

    reply
    0
  • Cancelreply