js 对于“属性”的操作有两个:attribute 特性 和 property 属性,看起来都是操作的“ele.属性”,那为什么会有不同?
以语言来区分的话:
- attribute 是 html 上的属性
- property 是 js 对象上的属性
attribute
attribute:代指 DOM 属性节点,是 html 标签上的某个属性,其值只能是字符串。如 id、class、value、title、alt 及自定义属性。它的值都是 string 类型。关于这个“属性”一共有三个相关的方法:
- 设置 setAttribute(attr, value)
- 获取 getAttribute(attr)
- 删除 removeAttribute(attr)
比如在代码段
中,打印 div 元素的 id 可以得到结果 box,id 就属于 html 的属性,属于 attribute。property
property:泛指 js 对象的属性,例如在自定义对象 const obj = { name : “zhangsan” ; age : 18 } 中的 name 和 age 就属于 property。
关联
DOM,本就是 html 与 js 间的接口,常用的 attribute 比如 id、class、name、value、src、title 等,一般也都会作为 property 附加到 js 对象上,可以和 property 一样取值、赋值。对于
中的 id,既是 html 属性节点 attribute,同样也是这个节点对象的 property。js 获取的 DOM 对象上的属性,可以将这个元素节点看作为一个基本的 js 对象。这个节点包括很多 property,比如
- 与节点自身关系相关的 children、parentNode、nextElementSibing 等
- 与自身样式相关的 clientWidth、clientLeft、offsetWidth、innerText 等
- 事件 onclick 等
常用的 attribute,如 id、class、title 等一般都会作为 property 附加到 js 对象上,可以和 property 一样取值、赋值。
总结
- property 和 attribute 都是 properties 的子集,而每个 attribute 是 attributies 的子集
- attribute 可以理解为特性,可以自定义,直接在 html 标签上添加的和使用 setAttribute() 添加的情况一致,即 html 标签添加的都是 attribute 属性, property 则是使用 xx.属性 进行更改,通常来讲,更改互相影响
- 当添加新的非默认属性时,是不互通的
- 一些特殊属性,则需要特殊对待
