方法获取属性

一、方法获取属性(上课笔记)

小注意点  可以在标签上自定义标签属性名

格式:data-xxxxx

自定义标签的获取

   1.通过方法  getAtribute('key') 获取

   2通过属性获取 标签.dataset.price

    //注意 自定义属性不能直接用元素点(box1.name)的方式去获取,要先获取dataset属性

下面是案例

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

<!--     data-xxxx :自定义属性 -->

    <div id="box" name="para" class="main" data-index="1" data-price="99.88">盒子</div>

    <script>

       var box1= document.querySelector('#box');

       console.log(box1)

       //可以获取元素的属性和方法

       console.dir(box1);

       

       // .attributes 获取指定原素上的所有属性

       console.log(box1.attributes);

       //.getAttribute('key') 通过方法获取标签上的属性

       console.log(box1.getAttribute('id'));

         

       //setAttribute('key','value') 添加和修改标签的属性

       box1.setAttribute('class','qwe');

       //removeAttribute('key')移除标签的属性

       box1.removeAttribute('name');

       //自定义属性的获取 (标签上的data-)

       //注意 自定义属性不能直接用元素点(box1.name)的方式去获取,要先获取dataset属性

       console.log(box1.getAttribute('data-index'));

       console.log(box1.dataset.price);

       console.log(box1.dataset.index);

    </script>

</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值