attribute 和 property 的区别

734 阅读1分钟

前言

attribute 是 HTML 标签上的特性,也就是 html 代码中经常看到的键值对

property 是 DOM 中的属性,是 JavaScript 里的对象

示例

attribute 会始终保持 html 代码中的初始值, 而 Property 是有可能变化的.


<input id="the-input" type="typo" value="Name:" customAttr="customAttr" /> 
// 在页面加载后,在input中输入 "Jack"
// type 属性给的值为 typo,并不属于 input 支持的 type 种类

input.getAttribute('id') // the-input
input.getAttribute('type') // typo
input.getAttribute('value') // Name:
input.getAttribute("customAttr") // customAttr

input.id // the-input
input.type // text
input.value // Jack
inout.customAttr // undefined

在 attribute 中,值仍然是 html 代码中值,而在 property 中,type 被修正为 text,value 的值也随用户输入而对应改变。

可以成功的获取自定义的 attribute ,但是无法获取 property。

DOM 节点在初始化的时候会将 html 规范中定义的 attribute 赋值到 property 上。而自定义的 attribute 并不属于这个范围内,自然生成的 DOM 节点就没有这个 property。

区别

Attribute
  • 值只能为 string 类型

  • 如果编辑 HTML 时设置了元素的 attribute 值,之后就算改了这个值,attribute 依旧是默认的值。

  • 允许创建自定义的值

property
  • 值可以是多种类型:boolean,string,number等都可以

  • 可以通过 DOM 对象访问

  • 或许不到规定属性以外的自定义属性

参考

前端杂谈: Attribute VS Property

Attribute和Property的区别