页面结构
<button id="btn" title="一个按钮"
type="button" index='123' abc='你好'>按钮</button>
对象的属性(自带标签)
元素自带标签会在页面获取dom对象的时候自动转为对象的属性放入对象中,所以自带标签可以直接用 对象.属性 取出,而自定义属性不可以
console.log( btn.title );
console.log( btn.id );
console.log( btn.type );
console.log( btn.className );
可以直接获得属性值,也可以直接为属性赋值;
标签的属性(自定义属性)
为标签设置的自定义属性在获取页面元素对象的时候并不会转为属性,所以并不能直接获取和赋值,要借助一个API才能获取
对象.getAttribute( 属性字符串 )
而这个API是直接从标签中获取属性,所以无论是自定义属性还是自带属性都能获取或者赋值;
获取
console.log( btn.getAttribute('id') );
console.log( btn.getAttribute('type') );
console.log( btn.getAttribute('title') );
console.log( btn.getAttribute('index') );
console.log( btn.getAttribute('abc') );
赋值API:对象.setAttribute(属性字符串,属性值)
btn.setAttribute('data-src','img/01.jpg');
btn.setAttribute('class','btn');
注:这里如果设置标签属性class,参数是字符串,直接写class,而不是直接获取时候的className;
删除标签属性API:对象.removeAttribute(属性字符串);
btn.removeAttribute('abc');