property和attribute的一些区别

自定义属性(id/src/href/name/value等)

  1. 通过setAttribute设置的自定义属性,可以通过prop(即.)的方式获得属性值

  2. 通过prop(即.)设置的属性,通过getAttribute不一定能得到属性值。(id,class,name,href等自定义属性可以)

value,checked属性

input标签

通过setAttribute设置value,checked属性,可以通过prop(即.)的方式获得属性值

通过prop(即.)设置value,checked属性,通过getAttribute得到的不是最新的值,得到的是原先的值

即两者是不同步的

// html
<input type="text" class="input">

// js
var inp = document.querySelector('.input');
inp.setAttribute('value', 'ababab');
console.log(inp.value);   // ababab
inp.value = "abcdefg";
var val = inp.getAttribute("value");
console.log(val)  //  ababab

src,href属性

通过prop(即.)的方式,得到的是完整的路径

通过getAttribute的方式,得到的是实际值

// html
<img src="./img/demo.jpg" class="image" />

// js
var img = document.querySelector('.image');
console.log(img.src)    //  file:///C:/Users/Administrator/Desktop/img/demo.jpg
console.log(img.getAttribute('src'))    // ./img/demo.jpg
    原文作者:laohan
    原文地址: https://www.jianshu.com/p/7dd14dac231f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞