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>

注意

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

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

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);

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

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']);

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