Can't use foreach loop on HTML collection
P粉930534280
2023-08-29 09:48:35
<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>
You should not use
forEach
because HTMLCollections does not implement the forEach method.Use for loop