attribute和property的区别

前言

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的区别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值