attribute与property的区别

  • attribute是HTML元素的特性,property是Dom节点的属性
  • 访问方式不同:attribute通过el.getAttribute(key)el.setAttribute(key, value)来访问和设置值;property则是通过el.fooel.foo = xxx这种方式来访问和设置值。
  • 某些情况下,attribute和property存在一对一的映射关系,比如id,title等。
const div = document.createElement('div')
// 设置attribute
div.setAttribute('id', 'foo')
// 获取attribute,值为foo
div.getAttribute('id')
// 获取property,值为foo,说明有映射关系
div.id
// 反向设置property
div.id = 'bar'
// 获取attribute,值为bar,进一步证明了映射关系
div.getAttribute('id')
  • 某些情况下,attribute和property存在一对一的映射关系,但是名称不同,比如attribute中叫class,但作为property则为className
  • 对于某些自定义的情况,attribute和property并不存在映射关系。
const div = document.createElement('div')
// 设置property
div.foo = 'foo'
// 获取property,值为foo
div.foo
// 获取attribute,值为null,说明设置了property并没有设置同名的attribute
div.getAttribute('foo')

// 反向操作一下
// 设置attribute
div.setAttribute('bar', 'bar')
// 获取attribute,值为bar
div.getAttribute('bar')
// 获取property,值为undefined,说明设置了attribute并没有设置同名的property
div.bar
  • 另外,从上面的代码还能得到一个另外的结论:attribute获取不到返回null,property获取到不到返回undefined。

  • attribute的值只能是字符串,property的值可以是其它类型。

const div = document.createElement('div')

div.setAttribute('number', 1)
div.setAttribute('boolean', true)
div.setAttribute('array', [1,2,3])
div.setAttribute('object', {foo: 'foo'})
div.getAttribute('number')  // '1'
div.getAttribute('boolean') // 'true'
div.getAttribute('array') // '1,2,3'
div.getAttribute('object')  // '[object Object]'

div.num = 1
div.bool = true
div.arr = [1,2,3]
div.obj = {foo, 'foo'}
div.num // 1
div.bool // true
div.arr // [1,2,3]
div.obj // {foo, 'foo'}
  • attribute从语义上, 更倾向于不可变更的值;而property从语义上更倾向于在其生命周期中是可变的值,其会修改不正确的值。
const input = document.createElement('input')
// 给input的type这个attribute设置一个错误的值
input.setAttribute('type', 'text2')
// attribute会返回最初设置的值,即使这个值是不正确的
input.getAttribute('type')  // text2
// property会修改不争取的值,因为不存在值未text2的type,所以它会返回默认值text
input.type  // text

如果一个input有初始value,用户输入导致value变化后,attribute不会变,但是property会变

<input value="1" />
// 用户把input框的值改为2后,attribute不变,property会变
input.getAttribute('value') // 1
input.value // 2
Last Updated: