区别
简单理解,attribute指html标签上属性,property指dom元素对象上的属性。
一般情况下property无法获取html标签自定义属性,比如
<div dname="haha">自定义标签属性</div>
console.log(document.querySelector('div').dname)//输出undefined
console.log(document.querySelector('div').getAttribute('dname'))//输出haha
而attribute无法获取html标签上没写的属性,比如
<input type="checkbox" value="Mickey">
console.log(document.querySelector('[type=checkbox]').getAttribute('checked'))//输出null
console.log(document.querySelector('[type=checkbox]').checked)//输出false
使用
一般情况下我们使用attribute就可以了,一般像input标签中的checked布尔值属性时使用property。看考jquery中attr()和prop()。