getAttribute / setArribute
getAttribute
attribute = element.getAttribute(attributeName)
读取指定的属性,例如
var inputname = document.getElementById('username')
var classin = inputname.getAttribute('class')
console.log(classin); //u-txt
示例获取了username的class属性值
setArrtribute
element.setAttribute(attributeName,value)
attributeName:要写的属性名
value:属性值
写入指定的属性,例如
var inputname = document.getElementById('username')
inputname.setAttribute('disabled','disabled')
通过getAttribute获取到的属性值是string类型
property accessor
属性访问器,可以通过DOM树来获取属性
var inputname = document.getElementById('username')
var a=document.querySelector('label');
console.log(a.htmlFor);
console.log(inputname.id); //等同于inputname['id']
console.log(inputname.type);
console.log(inputname.className);
inputname.id这种方式访问等同于inputname['id']
另外,如果要对属性进行写入,那么可以通过直接赋值来写入,例如
var inputname = document.getElementById('username')
var a=document.querySelector('label');
inputname.id=‘aaa’
通过DOM树获取的属性类型,是属性对应的类型
通过getArrtibute和property accessor的区别
通用性上get/set这种方式更强,但是返回的均是字符串,而property accessor通用性稍弱,因为名字存在异常(比如,上文获取类名不是inputname.class而是inputname.className),但是返回的类型是属性对应的类型
自定义属性
- 主要是元素中存储额外的信息
- 以data-*开头
- HTMLElement.dataset获取,当然getArrtibute也可以访问
<div>
<input id="username1" data-id="123" data-count-name-asd='xa' data-email='asd' data-mobile='111' type="text" class="u-txt">
</div>
var inputname = document.getElementById('username1')
var data = inputname.dataset;
console.log(data.id); //123
console.log(data.countNameAsd); //xa
console.log(data.email); //asd
案例
自定义属性通常会使用附加信息上,例如
有一个用户列表,当鼠标移动到列表上的某个用户上时,会弹出用户的联系方式,邮箱,手机号等,那么这些信息会以自定义属性的方式附加在用户列表的每个用户上