js获取属性和自定义属性操作

1.内置属性 和 自定义属性

element.属性 获取内置属性值(元素本身自带的属性)
element.属性 = ‘值’ 设置内置属性值
element.sermoverAttribute(‘要移除的属性’);
 <script>
        var div = document.querySelector('div');
        // 1. 获取元素的属性值
        // (1) element.属性
        console.log(div.id);
      
  //(2) element.getAttribute('属性')  get得到获取 attribute 属性的意思 我们程序员自己添加的属性我们称为自定义属性 index
        console.log(div.getAttribute('id'));
        console.log(div.getAttribute('index'));


        // 2. 设置元素属性值
        // (1) element.属性= '值'
        div.id = 'test';
        div.className = 'navs';


        // (2) element.setAttribute('属性', '值');  主要针对于自定义属性
        div.setAttribute('index', 2);
        div.setAttribute('class', 'footer'); // class 特殊  这里面写的就是class 不是className


       // 3 移除属性 removeAttribute(属性)    
        div.removeAttribute('index');
    </script>

注意
在这里插入图片描述

在这里插入图片描述

2.H5自定义属性

  • 自定义属性目的: 是为保存并使用数据。有些数据可以保存到页面中而不用保存到数据库中。
  • 自定义属性获取是通过getAttribute(‘获取’)获取。
  • 但是有些自定义属性容易引起歧义,不容易判断是元素的内置属性还是自定义属性。
  • H5给我们新增了自定义属性:

1.H5规定自定义属性

  • H5规定自定义属性 data - 开头作为属性名并且赋值。
  • 或者使用 Js设置
 - element.setAttribute( ‘data-index’ , 2);

2.获取H5自定义属性

1.兼容性获取 element.getAttribute(‘data-index’ );

2.H5新增 elemen.dataset.index 或者 element.dataset[‘index’] ie11 才支持

 var div = document.querySelector('div');
   /*  console.log(div.getAttribute('getTime')); */
    div.setAttribute('data-index',344);
    console.log(div.dataset.index);

在这里插入图片描述

var div = document.querySelector('div');

       console.log(div.getAttribute('getTime'));
        div.setAttribute('data-time', 20);
        console.log(div.getAttribute('data-index'));
        console.log(div.getAttribute('data-list-name'));
        // h5新增的获取自定义属性的方法 它只能获取data-开头的

** // dataset 是一个集合里面存放了所有以data开头的自定义属性**

        console.log(div.dataset);
        console.log(div.dataset.index);
        console.log(div.dataset['index']);

// 如果自定义属性里面有多个-链接的单词,我们获取的时候采取 驼峰命名法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

都挺好,刚刚好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值