getattribute()读取html源码中写死的属性值,不反映运行时状态;如用户修改input内容后,getattribute('value')仍返回初始值,而点号访问的value property才获取当前值。

直接用 getAttribute() 和 setAttribute(),但必须清楚它们只管 HTML 属性(attribute),不等于 DOM 属性(property)——比如 input.value 的当前值就不是 getAttribute('value') 能拿到的。
getAttribute() 为什么有时拿不到最新值?
它读的是 HTML 源码里写死的属性值,不是运行时变化后的状态。例如:
<input id="user" value="初始值">
用户手动输入“新内容”后:
-
document.getElementById('user').value→ 返回 "新内容"(DOM property) -
document.getElementById('user').getAttribute('value')→ 仍返回 "初始值"(HTML attribute)
布尔属性(disabled、checked、selected)更典型:未设置时 getAttribute('disabled') 返回 null,设了就返回字符串 "disabled",不是布尔值。
修改 class、id、style 这类常用属性,该用点号还是 setAttribute?
优先用点号访问(el.className、el.id、el.style.color),更直接、性能好、语义清晰。
-
el.className = 'active highlight'等价于el.setAttribute('class', 'active highlight'),但前者更常见 -
el.id = 'new-id'安全可用,但要注意全局唯一性,避免重复id导致getElementById行为异常 -
el.style.display = 'none'是标准写法;用setAttribute('style', 'display:none;')会覆盖整个style字符串,容易误删其他内联样式
data-* 自定义属性,用 dataset 还是 getAttribute?
用 dataset,除非你要读取带数字开头或特殊符号的 key(如 data-1st-place)。
<div data-user-id="100" data-api-url="/v1"></div>-
el.dataset.userId→"100"(自动转驼峰) -
el.dataset.apiUrl→"/v1" -
el.dataset['1st-place']→ 必须用方括号访问 -
dataset是只读映射,改它不会更新 HTML;要写入,仍得调setAttribute('data-user-id', '101')
removeAttribute 和直接赋值为 null/undefined 有区别吗?
有。只有 removeAttribute() 会真正从元素上删掉这个属性节点;赋值为 null 或 undefined 只是让对应 property 失效,HTML attribute 依然存在。
-
el.disabled = null→ 元素仍不可交互(disabledproperty 为 true),且getAttribute('disabled')仍返回"disabled" -
el.removeAttribute('disabled')→ 移除属性,元素恢复可交互,getAttribute('disabled')返回null
这个细节在表单控件和可访问性(a11y)检查中容易被忽略,尤其做动态启用/禁用逻辑时。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











