HTML Collection无法使用forEach,修改H1文本失败求助
问题诊断与解决方案
你的代码问题出在HTMLCollection没有内置的forEach方法——getElementsByTagName()返回的是HTMLCollection类型,它是类数组对象,但不属于数组,无法直接调用数组的forEach遍历方法,所以你的循环逻辑根本没执行。
解决方法有以下几种:
1. 将HTMLCollection转为数组后使用forEach
用Array.from()把类数组转成真正的数组:
const a = document.getElementsByTagName("body")[0]; const d = a.getElementsByTagName("h1"); Array.from(d).forEach(element => { element.innerHTML = "the text has changed"; });
2. 借助数组原型的forEach方法
通过call()绑定HTMLCollection对象来调用数组的forEach:
const a = document.getElementsByTagName("body")[0]; const d = a.getElementsByTagName("h1"); Array.prototype.forEach.call(d, element => { element.innerHTML = "the text has changed"; });
3. 使用普通for循环遍历
最稳妥的兼容写法,不用依赖数组方法:
const a = document.getElementsByTagName("body")[0]; const d = a.getElementsByTagName("h1"); for (let i = 0; i < d.length; i++) { d[i].innerHTML = "the text has changed"; }
4. 改用querySelectorAll获取NodeList
querySelectorAll()返回的NodeList对象在现代浏览器中支持forEach方法,写法更简洁:
const d = document.querySelectorAll("body h1"); d.forEach(element => { element.innerHTML = "the text has changed"; });
内容的提问来源于stack exchange,提问作者DavTra
相关产品推荐
相关产品推荐

