通过document.getElementsByClassName等方式获取的是HTMLCollection(一个包含了顺序为文档流中顺序的元素的通用集合), 不是一个数组,不能直接使用 forEach 等进行遍历。
解决方案:将HTMLCollection转换成数组
方法很多,其中最简单的一种是使用解构运算符 ... (注意:每一层都需要解构)
// 遍历整个文档的div标签[...document.getElementsByTagName("div")].forEach(item => {// 遍历div内的元素[...item.children].forEach(item2 => {console.log(item2.tagName) // 元素的标签名console.log(item2.innerText) // 元素内的文本内容console.log(item2.offsetTop) // 元素距离整个文档顶部的距离})}),