如果想获取多个可以使用:
看例子
<template>
<div class="app">
<div class="box" >
<div class="box1">box1</div>
<div class="box1">box2</div>
</div>
</div>
</template>
<script>
export default {
name: 'app',
data(){
return {
isTrue:true
}
},
mounted(){
let box1s = document.getElementsByClassName("box1")
console.log("box1s",box1s); // HTMLCollection(2) [div.box1, div.box1]
console.log("box1s",box1s.length); // 2
console.log("box1s",typeof box1s); // object
// box1s.map(item=>{ 可能长得像list但是是个object所以这个使用map会报错
// return item 所以不能用这种方式进行循环遍历
// })
// for(let box in box1s){ // 不能用这种方式循环遍历 原因看分析
// console.log(box) // 所以也不能用这种方式进行循环遍历
// if(box>=box1s.length){
// continue
// }
// console.log(box)
// }
for(let i=0; i<box1s.length;i++){
box1s[i].style.backgroundColor="yellow"
}
},
methods:{
}
}
</script>
结果如下:
分析如下: