JavaScript 查找dom节点 ClassName 后操作节点

直接上代码 重点在script部分

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  .names{
    width: 10rem;
    height: 10rem;
    text-align: center;
    line-height: 10rem;
    font-size: 2rem;

    background-color: black;
    color: rgb(1, 126, 243);
  }
</style>
<body>
  <div class="names">1</div>
  <div class="names">2</div>
  <div class="names">3</div>
  <div class="names">4</div>
  <script>
    let list=document.getElementsByClassName('names')
    // 直接查找 dom 的class节点你会得到一组伪数组,
    // 这样的数组你是没办法操作
    // 所以要转化
    
    // 方法A slice会把通过索引位置获取新的数组,该方法不会修改原数组,只是返回一个新的子数组
    //      call会把this的指向改为传进去的obj
    let listA=[].slice.call(list);
    listA[0].style.backgroundColor="red"
    
    // 方法B Array.from() 静态方法
    //      从可迭代或类数组对象创建一个新的浅拷贝的数组实例。
    let listB=Array.from(list)
    listB[1].style.backgroundColor="pink"
    console.log(listB,);

    // 方法C ES6的扩展运算符 解构
    let listC=[...list];
    listB[2].style.backgroundColor="yellow"

  </script>
</body>
</html>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值