getAttribute/setAttribute仅操作HTML属性而非DOM属性;如input.value是property,getAttribute('value')读初始值而非用户输入值;需区分使用场景,避免设了没生效或读错。
它们只处理 HTML 属性(attribute),不是 DOM 属性(property)。比如 input.value 是 property,而 input.getAttribute('value') 读的是初始 HTML 中写的值,不是用户输入后的真实值。混淆这两者,是绝大多数“设了没生效”或“读出来不对”的根源。
只在需要读写**HTML 源码中显式声明的属性**时才该用。典型场景包括:
data- 自定义属性:如 getAttribute('data-id')、setAttribute('data-loaded', 'true')
hasAttribute('disabled')(注意不是 getAttribute('disabled') === 'disabled')class 属性要完整读取 HTML 写的值(不含 JS 动态添加的类)xmlns、role)或 SVG 特有属性(如 viewBox)以下属性修改 setAttribute 后看似成功,但 UI 或逻辑不会响应变化:
value:对 设定后只影响初始值,不更新当前显示内容;应直接赋值 el.value = 'xxx'
checked / selected / disabled:这些是布尔 property,设为 setAttribute('checked', 'checked') 只影响 HTML 源码,不触发控件状态切换;正确做法是 el.checked = true
style:虽然 setAttribute('style', 'color:red') 能生效,但会覆盖全部内联样式;推荐用 el.style.color = 'red' 或 el.style.cssText += ';color:red'
innerHTML:根本不是属性,是 property;setAttribute('innerHTML', '...') 会变成一个无意义的 HTML attributegetAttribute 和 setAttribute 在所有现代浏览器中行为一致,但要注意:
getAttribute 返回 null(不是 undefined),做严格比较时别漏掉null 给 setAttribute,会设成空字符串值,而非移除属性;要移除得用 removeAttribute
className 或 classList 比反复 setAttribute('class', ...) 更快且安全fill、cx)时,部分旧版 IE 要求用 setAttributeNS,但现代环境基本可忽略const el = document.querySelector('input');
el.setAttribute('value', 'new'); // 不改变当前输入框显示内容
console.log(el.getAttribute('value')); // 'new'(HTML 属性值)
console.log(el.value); // 用户当前输入的内容,或原 value 属性初始值
el.value = 'updated'; // 正确更新显示值
el.setAttribute('data-status', 'done'); // 正确写自定义属性
el.removeAttribute('data-temp'); // 正确移除,而不是 setAttribute('data-temp', null)
真实 DOM 操作里,属性和 property 的边界比文档描述得更模糊——尤其在表单控件和事件绑定之后,property 状态可能已脱离 HTML attribute 的原始影子。动手前先问一句:我要改的是“HTML 文本里怎么写的”,
还是“这个元素此刻该怎么表现”。