JavaScript中property和attribute的区别
-
1. 定义
property(元素属性):DOM节点是一个对象,因此,可以添加自定义的属性以及方法。property的值可以是任何的数据类型,对大小写敏感。自定义的property不会出现在html中,只存在JavaSctipt中。attribute(标签属性):attribute只能是字符串,大小写不敏感,出现在innerHTML中,通过类数组attributes可以罗列所有的attribute。
-
2. 相同之处
-
标准
DOM的properties(元素属性)与attributes(标签属性)是同步的。公认的attributes(标签属性)会添加到DOM对象property(元素属性)上,如id、style、className、disabled、checked等。这时候直接操作property (el. checked)或者使用el.getAttribute() / el.setAttribute()效果一致。但是参数不一定相同,如:el.className 与 el.getAttribute('class') -
3. 不同之处
-
对于有些标准的特性的操作,
el.getAttribute 与 el.property获取的值存在差异性。如: `href、src、value、style、onclic 等 -
Demo1:el.getAttribute 获取的是 href 的实际值,el.property 获取的是完整的 url
alEl.href = '/';
alert(alEl.getAttribute('href')); // '/'
alert(alEl.href); // full URL
@前端进阶之旅: 代码已经复制到剪贴板
Demo2:el.property 可以从 el.setAttribute 获得同步
inputEl.setAttribute('value', 'hello');
alert(inputEl.value ); // 'hello' -- property changed!
@前端进阶之旅: 代码已经复制到剪贴板
- Demo3: el.getAttribute 不能从 el.property 获得同步
inputEl.value = 'bye';
alert(inputEl.getAttribute('value')); // 'hello' – attribute not changed!
@前端进阶之旅: 代码已经复制到剪贴板
- Demo4:el.getAttribute 只能获取输入框的原始值,el.property 可以获取输入框修改后值
用户输入 ‘good’,inputEl.value 获得 ‘good’,inputEl.getAttribute(‘value’) 获得原始值 ‘hello’。 可以利用 inputEl.value == inputEl.getAttribute(‘value’) 检验 input 是否变化
- Demo5:checkbox 未选中时 – el.getAttribute 返回 null,el.property 返回 false
checkbox 选中时 – el.getAttribute 仍返回 null,el.property 返回 ture
alert(checkboxEl.checked); // boolean true