我有两个文件,一个是js:
const a = document.getElementsByTagName("body")[0];
const d = a.getElementsByTagName("h1");
d.forEach(element => {
element.innerHTML = "the text has changed";
});
和HTML文件:
<!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>
我试图将每个h1元素的文本更改为相同的文本,但它不起作用,这意味着当我在浏览器上运行它时,所有的"h1"文本保持不变。
不知道为什么,因为"d"是一个HTML集合,我用foreach在它上面运行。
基本上都是直截了当的,所以不确定我能尝试什么。
感谢任何帮助!
你不应该使用forEach
,因为HTMLCollections不实现forEach方法。
使用for循环
const a = document.getElementsByTagName('body')[0]
const d = a.getElementsByTagName('h1')
for (let elem of d) {
elem.innerHTML = 'new text'
}