attribute 和 property 的区别

property 和 attribute 容易混淆,两个单词的中文翻译也很相近(property:属性,attribute:特性),但实际上是不同的东西,属于不同的范畴。

  • Attribute:DOM 节点自带的属性,例如 HTML 中常用的 id、class、title、align 等。
  • Property:DOM 元素作为对象,其附加的内容,例如 childNodes、firstChild 等。

attributes 是属于 property 的一个子集,它保存了 HTML 标签上定义的属性。如果再深入看 attributes 里的每一项,会发现它们并不是简单对象,而是 Attr 类型的对象,拥有 NodeType、NodeName 等属性。

凡是 DOM 标签里出现的属性(HTML 代码),都是 Attribute。然后部分常用特性(id、class、title 等)会被转化为 Property。

<div id="div1" class="divClass" title="divTitle" title1="divTitle1">100</div>

上面 div 里的 title1 就不会变成 Property。

1. 取值与赋值

Attribute

通过 setAttribute() / getAttribute() 操作:

div1.setAttribute('data-id', '1');
div1.getAttribute('data-id'); // '1'

Property

用 . 即可访问:

const id = div1.id;
const className = div1.className;
const childNodes = div1.childNodes;
const attrs = div1.attributes;

2. 同步关系

  • 大多数标准 Attribute 会和对应的 Property 互相映射(如 id、class → className)。
  • 自定义属性(如 data-*)一般只存在于 Attribute,不会映射成 Property。
  • 布尔型属性(如 disabled、checked)通过 Property 同步更可靠。

来源整理自:我的有道云笔记