getAttribute/setAttribute 操作 HTML 屬性(Attribute),區別於 DOM 屬性。掌握兩者差異對跨瀏覽器開發至關重要。
<li id="li1" title="hello">Magic</li>
<button onclick="changeAttr()">修改</button>
<script>
function changeAttr(){
const el = document.getElementById('li1');
console.log(el.getAttribute('title')); // "hello"
el.setAttribute('title', 'mgc');
console.log(el.getAttribute('title')); // "mgc"
}
</script>
| 維度 | Attribute (get/setAttribute) | Property (el.prop) |
|---|---|---|
| 定義 | HTML 標簽屬性,字符串 | DOM 對象屬性,任意類型 |
| 同步 | 單向:HTML→DOM 初始化 | 雙向:修改 property 多數同步到 attribute |
| 典型差異 | value、checked、selected、class | 實時狀態、對象引用、布爾值 |
el.getAttribute('value') 返回初始 HTML 值,非用戶輸入後的值 → 用 el.value。el.setAttribute('class', 'c') IE6/7 無效 → 用 el.className = 'c' 或 el.classList.add('c')。el.getAttribute('style') 返回 CSS 文本 → 用 el.style.cssText 或 el.style.prop。data-*,配合 dataset API:el.dataset.userId。// attr() 操作 attribute,prop() 操作 property
$('#chk').prop('checked', true); // 勾選
$('#chk').attr('checked', 'checked'); // 初始屬性
$('#inp').val('text'); // value 專用
.prop()。data-* + .data()。.attr()。.addClass()/removeClass()/toggleClass()。