3 回答
TA贡献1876条经验 获得超7个赞
您可以Array.from将像对象这样的数组转换为真实数组。然后使用一些数组方法进行迭代。
let array = Array.from(document.getElementsByClassName('dummy'));
array.forEach((e) => {
console.log(e);
});
<div class = "dummy">Test1</div>
<div class = "dummy">Test2</div>
TA贡献1111条经验 获得超0个赞
您还可以使用传播语法
[...document.getElementsByClassName('dummy')].forEach((e) => {
e.classList.add('test')
});
.test {
color: green;
}
<div class="dummy">Test1</div>
<div class="dummy">Test2</div>
TA贡献1829条经验 获得超7个赞
使用Array.from,slice或...(展开):
var divs = [...document.getElementsByClassName('dummy')]
divs.forEach(d => console.log(d));
var divs2 = Array.from(document.getElementsByClassName('dummy'));
divs2.forEach(d => console.log(d));
var divs3 = Array.from(document.getElementsByClassName('dummy'));
divs3.forEach(d => console.log(d));
<div class="dummy">Test1</div>
<div class="dummy">Test2</div>
添加回答
举报