| 概念 | Property (屬性) | Attribute (特性/屬性) |
|---|---|---|
| 所屬 | DOM 對象 (JS 對象) | HTML 標籤標記 |
| 值類型 | 任意 JS 類型 | 僅字符串 |
| 大小寫 | 敏感 | 不敏感 |
| 可見性 | 不出現在 outerHTML | 出現在 outerHTML / innerHTML |
| 訪問方式 | el.prop / el['prop'] | el.getAttribute() / el.setAttribute() |
標準屬性雙向同步:id、className/class、title、style、href、src、value (輸入框) 等。
// 修改 property → attribute 同步更新
el.id = "newId";
el.getAttribute("id"); // "newId"
// 修改 attribute → property 同步更新
el.setAttribute("title", "tip");
el.title; // "tip"
<a id="a" href="/path">
a.href; // "https://domain.com/path" (解析後絕對路徑)
a.getAttribute('href'); // "/path" (HTML 原始值)
<input value="init">
el.setAttribute('value', 'new'); // attribute & property 都變 'new'
el.value = 'user input'; // property 變 'user input', attribute 仍為 'new' (原始值)
// 用途:通過 attribute 獲取初始值實現重置功能
el.style; // CSSStyleDeclaration 對象
el.getAttribute('style'); // "color: red;" 字符串
el.onclick; // Function 對象
el.getAttribute('onclick'); // "handler()" 字符串
<input checked>
el.checked; // true (Boolean)
el.getAttribute('checked'); // "" (空字符串, 存在即 true)
el.hasAttribute('checked'); // true (推薦檢測方式)
getAttribute/setAttribute 可互訪 property,大小寫不敏感導致衝突:// IE8 兼容模式
document.body.abba = 1;
document.body.ABBA = 5;
document.body.getAttribute('ABba'); // 返回 1 (首次出現的值),而非 5
el.id、el.className、el.value、el.checked、el.style.color、el.dataset.xxx。el.getAttribute('data-x') / el.dataset.x (HTML5 推薦)。href/src/value 未解析值。el.hasAttribute('disabled')。viewBox)。.prop() 操作 Property,.attr() 操作 Attribute,.data() 操作 data-* 緩存 (不同步到 DOM)。