首页  >  问答  >  正文

无法在HTML集合上使用foreach循环

<p>我有两个文件,一个是js文件:</p> <pre class="brush:php;toolbar:false;">const a = document.getElementsByTagName("body")[0]; const d = a.getElementsByTagName("h1"); d.forEach(element => { element.innerHTML = "文本已更改"; });</pre> <p>还有一个是html文件:</p> <pre class="brush:php;toolbar:false;"><!DOCTYPE html> <html lang="en"> <head> <title>David </title> </head> <body> <h1>你好1</h1> <h2>大卫</h2> <h3>亚里尔</h3> <h4>雅哈夫</h4> <h1>你好2</h1> <h1>你好3</h1> <script src="food.js"></script> </body> </html></pre> <p>我试图将每个h1元素的文本更改为相同的文本,但是它没有起作用,也就是说当我在浏览器上运行时,所有的"h1"文本仍然保持不变。</p> <p>不确定为什么,因为"d"是一个html集合,我用foreach在它上面运行。</p> <p>基本上一切都很简单,所以不确定我可以尝试什么。</p> <p>感谢任何帮助!</p>
P粉930534280P粉930534280417 天前487

全部回复(1)我来回复

  • P粉864594965

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

    你不应该使用forEach,因为HTMLCollections没有实现forEach方法。

    使用for循环

    const a = document.getElementsByTagName('body')[0]
    const d = a.getElementsByTagName('h1')
    
    for (let elem of d) {
        elem.innerHTML = '新文本'
    }

    回复
    0
  • 取消回复