HTML attribute 和 DOM property,根本不是一回事

先看看下面这三行代码:

html 复制代码
<button disabled="false">提交</button>
<input value="A">
<a href="../docs/x.html">文档</a>

按钮没禁用

输入框里是 A

链接是相对路径。

实际呢?

  • button.disabled === true------disabled="false" 仍然算禁用;
  • 用户往输入框里打了 B,input.value === "B",但 input.getAttribute('value') 还是 "A";
  • a.href 是 https://example.test/dir/docs/x.html,而 getAttribute('href') 才是 "../docs/x.html"。

这是因为 HTML attribute 和 DOM property 不等价。写的 HTML 是标记,JS 读写的是对象;两者有时同步,有时完全不同步。

1. 它们的关系有几种呢?

HTML 里的 disabled、value、href 是 content attribute,存在标记里,值是字符串(或没有值)。

DOM 对象上的 disabled、value、href 是 IDL attribute(也就是 property),是 JS 对象上的字段,有类型:boolean、string、number、URL......

它们的关系有三种:

  • 反射 :property 读写会同步到 attribute,比如 className ↔ class、id、title。
  • 单向/带状态 :attribute 是"默认值",property 是"当前值",比如 value、checked、selected。
  • 不是一一对应 :名字不一样(readOnly ↔ readonly),类型不一样(maxLength 是 number),URL 会被解析成绝对地址。

所以HTML 里写什么,JS 就读什么是不对的,下面七个常见的问题可以一起验证一下这句话。

2.disabled="false"` 仍然是禁用

输入:

html 复制代码
<button disabled="false">提交</button>

实际结果:

js 复制代码
button.getAttribute('disabled')   // "false"
button.disabled                   // true
button.outerHTML                  // '<button disabled="false"></button>'

布尔 attribute 只知道你有没有,不管值是什么。只要 disabled 这个 attribute 存在,无论值是 "false"、"0"、"no",button.disabled 结果都是 true。

反过来,用 property 改:

js 复制代码
button.disabled = false
button.getAttribute('disabled')   // null
button.hasAttribute('disabled')   // false

button.disabled = true
button.getAttribute('disabled')   // ""
button.outerHTML                  // '<button disabled=""></button>'

还有一个很容易踩的坑:getAttribute('disabled') 在 <button disabled> 上返回的是空字符串 "",而 "" 是 false。所以:

js 复制代码
if (button.getAttribute('disabled')) { /* 不会进来 */ }

这个判断是错的。要么用 button.disabled,要么用 button.hasAttribute('disabled')。

避免写法:

布尔 attribute 用 property 或 hasAttribute,不要用 getAttribute 的真假值。

html 复制代码
<!-- disabled="false" 仍然是禁用 -->
<button disabled="false">提交</button>

<!-- 用 property 控制 -->
<button id="btn">提交</button>
<script>
  btn.disabled = true;   // 禁用
  btn.disabled = false;  // 启用
</script>

hidden、readonly、multiple、required 这些布尔 attribute 都是同一套规则。

3. value 属性是默认值,value` property 是当前值

输入:

html 复制代码
<form>
  <input name="x" value="A">
</form>

按顺序操作,结果:

js 复制代码
input.getAttribute('value')   // "A"
input.value                   // "A"
input.defaultValue            // "A"

input.value = 'B'
input.getAttribute('value')   // "A" 没变
input.value                   // "B"
input.defaultValue            // "A"

input.setAttribute('value', 'C')
input.getAttribute('value')   // "C"
input.value                   // "B" 当前值不变
input.defaultValue            // "C"

form.reset()
input.getAttribute('value')   // "C"
input.value                   // "C" 回到默认值
input.defaultValue            // "C"

核心是浏览器和HTML规范中,有一条 dirty value flag(脏值标记)规范:

  • input.value = 'B' 会把输入框标记为"脏",当前值就固定为 B;
  • 之后再改 value attribute,只改"默认值"(defaultValue),不会覆盖当前值;
  • form.reset() 把当前值重置回默认值,并清掉 dirty flag。

如果在变脏之前改 attribute:

js 复制代码
const input = document.createElement('input')
input.setAttribute('value', 'A')
input.setAttribute('value', 'C')
input.value                   // "C"

因为还没被用户/JS 改脏,改默认值会同时改当前值。

避免写法:

读当前值用 input.value,读默认值用 defaultValue 或 getAttribute('value'),别混。

js 复制代码
const current = input.value            // 用户现在看到的值
const initial = input.defaultValue     // reset 后会回到的值

input.value = 'B'                      // 改当前值
input.defaultValue = 'C'               // 改默认值(会影响 reset)

React 里的 value / defaultValue、Vue 里的 v-model / :value,本质上都在处理这两层。展开说:

3.1 React 和 Vue 分别怎么处理这两层?

一句话:React 把"当前值"交给 state,用 value + onChange 控制;Vue 用 v-model 把 :value + @input 绑在一起。两者最终都是写 DOM property(el.value),不是改 value attribute。

React

  • 受控输入:value={name} + onChange;每次输入 setName(e.target.value),重渲染时 React 把当前值写到 input.value。
  • 非受控输入:defaultValue="A" 只设初始/默认值,之后用 ref 读当前值。
  • checkbox 对称:checked / defaultChecked。
jsx 复制代码
import { useState } from 'react'

function Form() {
  const [name, setName] = useState('')

  return (
    <>
      {/* 受控:当前值由 state 决定 */}
      <input value={name} onChange={e => setName(e.target.value)} />

      {/* 非受控:只设默认值 */}
      <input defaultValue="A" />
    </>
  )
}

注意:<input value={name}> 不传 onChange 会变成只读;form.reset() 只重置 DOM 的默认值,不会自动改 React state------受控组件要在 onReset 里自己同步 state。

Vue 3

  • v-model 是语法糖:文本输入编译成 :value + @input;checkbox 编译成 :checked + @change;select 编译成 :value + @change。
  • :value 是单向绑定,v-model 是双向绑定。
  • v-model 没有单独的"默认值"概念:默认值就是 ref 的初值。
vue 复制代码
<script setup>
import { ref } from 'vue'

const name = ref('')
const agree = ref(false)
</script>

<template>
  <input v-model="name" />

  <!-- 等价写法 -->
  <input :value="name" @input="name = $event.target.value" />

  <input type="checkbox" v-model="agree" />
</template>

Vue 也是写 el.value / el.checked property;form.reset() 同样不会自动同步 ref,需要自己重置。

对照

React Vue 3
当前值 value + onChange v-model(或 :value + @input)
默认值 defaultValue / defaultChecked ref 初值(或直接写 value attribute)
写 DOM property(el.value) property(el.value)
原生 reset 要自己同步 state 要自己同步 ref

4. checked / selected 也是"默认 vs 当前"

先看 checkbox:

js 复制代码
checkbox.getAttribute('checked')   // ""
checkbox.checked                   // true
checkbox.defaultChecked            // true

checkbox.checked = false
checkbox.getAttribute('checked')   // "" attribute 还在
checkbox.checked                   // false
checkbox.defaultChecked            // true

checkbox.setAttribute('checked', 'false')
checkbox.getAttribute('checked')   // "false"
checkbox.checked                   // false 已经被改脏,不动当前值
checkbox.defaultChecked            // true

form.reset()
checkbox.checked                   // true 回到默认值

checked attribute 是"默认勾选",checked property 是"当前勾选"。用户点过之后,attribute 不会自动消失;它只在 reset 时重新生效。

selected 同理:

js 复制代码
select.value                       // "a"
option.getAttribute('selected')    // ""
option.selected                    // true
option.defaultSelected             // true

select.value = 'b'
option.getAttribute('selected')    // "" attribute 还在
option.selected                    // false
option.defaultSelected             // true

form.reset()
select.value                       // "a"
option.selected                    // true

避免写法:

切换当前状态用 property,设置"reset 后的默认状态"用 default*,不要用 setAttribute 去切当前状态。

js 复制代码
checkbox.checked = true
checkbox.defaultChecked = true

option.selected = true
select.value = 'b'

5. href / src 的 property 是绝对 URL

输入:

html 复制代码
<a href="../img/x.png">图片</a>

实际结果:

js 复制代码
a.getAttribute('href')   // "../img/x.png"
a.href                   // "https://example.test/dir/img/x.png"

getAttribute 返回你写的原始字符串;.href 返回浏览器按当前文档/base 解析后的绝对 URL。页面里有 <base href="https://example.test/dir/sub/"> 时:

js 复制代码
a.setAttribute('href', '../img/x.png')
a.href                   // "https://example.test/dir/img/x.png"

a.setAttribute('href', '/abs')
a.href                   // "https://example.test/abs"

a.href = 'rel/child.html'
a.getAttribute('href')   // "rel/child.html"
a.href                   // "https://example.test/dir/sub/rel/child.html"

注意最后一条:给 .href 赋相对字符串,attribute 也会被写成这个相对字符串,property 仍然是绝对 URL。img.src 也是一样:getAttribute('src') 是原始值,.src 是绝对地址。

避免写法:

拼 URL/跳转用 .href,要拿用户写的原始字符串用 getAttribute。

js 复制代码
const raw = a.getAttribute('href')   // "../img/x.png"
const absolute = a.href             // 解析后的绝对地址

6. class 和 style 也是两套账

class 这层比较直观:

js 复制代码
div.setAttribute('class', 'a b')
div.getAttribute('class')   // "a b"
div.className               // "a b"

div.classList.add('c')
div.getAttribute('class')   // "a b c"
div.className               // "a b c"

div.className = 'x'
div.getAttribute('class')   // "x"

classList 和 className 都是反射到同一个 class attribute 上的。

style 就有意思了哈

.style 是 CSSStyleDeclaration 对象,不是字符串。

js 复制代码
div.style.color = 'red'
div.getAttribute('style')   // "color: red;"
div.style.color             // "red"
div.style.cssText           // "color: red;"

div.setAttribute('style', 'color: blue; font-size: 20px')
div.getAttribute('style')   // "color: blue; font-size: 20px"
div.style.color             // "blue"
div.style.cssText           // "color: blue; font-size: 20px;"

改 .style.color 会同步到 style attribute;用 setAttribute('style', ...) 整段替换,会覆盖之前所有内联样式。

避免写法:

单个样式用 el.style.x,批量切换用 classList;不要用字符串拼整个 style attribute。

js 复制代码
el.classList.add('active')
el.style.color = 'red'

7. data-* 和 dataset 的命名转换

输入:

html 复制代码
<div data-user-id="42"></div>

JS 里:

js 复制代码
div.getAttribute('data-user-id')   // "42"
div.dataset.userId                 // "42"

data-* 到 dataset 的映射是 camelCase:data-user-id → dataset.userId,data-foo-bar → dataset.fooBar。

反向也通:

js 复制代码
div.dataset.userName = 'leo'
div.getAttribute('data-user-name')  // "leo"
div.dataset.userName                // "leo"

div.dataset.userName = '42'
typeof div.dataset.userName         // "string" 即使写数字也是字符串
div.getAttribute('data-user-name')  // "42"

delete div.dataset.userName
div.getAttribute('data-user-name')  // null

注意 dataset 的值永远是字符串;要数字/布尔自己转。

✅ 避免写法:JS 读写用 dataset,CSS 选择器/HTML 里用 data-*;不要手拼 dataset-user-id 这种不存在的属性名。

js 复制代码
el.dataset.userId = '42'
const id = el.dataset.userId

8. 实验 7:名字和类型都可能不一样

同一份 HTML,property 名字经常是 camelCase,类型也不是字符串:

js 复制代码
input.setAttribute('readonly', '')
input.readOnly                    // true
input.getAttribute('readonly')    // ""

input.setAttribute('maxlength', '5')
input.maxLength                   // 5(number)
input.getAttribute('maxlength')   // "5"

input.setAttribute('tabindex', '2')
input.tabIndex                    // 2(number)

label.setAttribute('for', 'x')
label.htmlFor                     // "x"

td.setAttribute('colspan', '2')
td.colSpan                        // 2(number)

规律:attribute 名通常是全小写;property 名是 camelCase(readOnly、maxLength、tabIndex、htmlFor、colSpan)。布尔 property 是 boolean,数字 property 是 number,getAttribute 永远是 string/null。

还有一个空值坑:attribute 不存在时,getAttribute 返回 null,property 给你默认值:

js 复制代码
input.getAttribute('value')       // null
input.value                       // ""

button.getAttribute('disabled')   // null
button.disabled                   // false
button.hasAttribute('disabled')   // false

所以别用 getAttribute(...) === '' 来判断"存在",用 hasAttribute;别用 getAttribute 的返回值判断布尔状态,用 property。

避免写法:

property 用 camelCase 和对应类型;判断存在用 hasAttribute。

js 复制代码
input.readOnly = true
input.maxLength = 5
input.tabIndex = 2
label.htmlFor = 'x'
cell.colSpan = 2

if (button.hasAttribute('disabled')) { /* ... */ }

9. 扩展:cloneNode 和 outerHTML 也不是一回事

如果要复制一个输入框,到底复制的是"当前值"还是"默认值"?

js 复制代码
input.setAttribute('value', 'A')
input.value = 'B'

input.getAttribute('value')   // "A"
input.value                   // "B"
input.outerHTML               // '<input value="A">'

const clone = input.cloneNode()
clone.getAttribute('value')   // "A"
clone.value                   // "B"   ← 当前值被复制了

outerHTML 只序列化 attribute,所以显示 A;

cloneNode 对表单控件有专门的 cloning steps,会把当前 value/checkedness 一起复制

所以 clone 的 value 是 B。

checkbox 同理:

js 复制代码
checkbox.setAttribute('checked', '')
checkbox.checked = false

checkbox.getAttribute('checked')   // ""
checkbox.checked                   // false
checkbox.outerHTML                 // '<input type="checkbox" checked="">'

const clone = checkbox.cloneNode()
clone.checked                      // false  ← 复制的是当前状态

outerHTML 看 attribute(默认),cloneNode 看当前状态(表单控件)。普通元素的 JS property 不会因为 cloneNode 自动复制,但 attribute 会。

避免写法:

要当前状态用 cloneNode,要默认标记用 outerHTML/getAttribute,不要拿 outerHTML当成当前值的快照或者副本之类的。

js 复制代码
const current = input.cloneNode()     // 当前 value/checked
const markup = input.outerHTML        // 属性默认值

面试题

Q1:<button disabled="false"> 为什么还是禁用的?怎么正确启用?

答:布尔 attribute 只看是否存在,disabled="false" 依然存在,所以 button.disabled 为 true。正确做法是用 property:button.disabled = false,或 removeAttribute('disabled')。

Q2:input.value 和 value attribute 是什么关系?form.reset() 回到哪个值?

答:value attribute 是默认值(defaultValue),input.value 是当前值。用户/JS 改过当前值后会置 dirty value flag,之后再改 attribute 只改默认值;reset 回到 defaultValue。

Q3:checked / selected 的 attribute 和 property 分别是什么?怎么正确切换?

答:attribute 是默认勾选/选中(defaultChecked / defaultSelected),property 是当前状态。切换当前状态用 checkbox.checked = ...、option.selected = ... 或 select.value = ...,不要用 setAttribute 去切当前状态。

Q4:a.href 和 getAttribute('href') 为什么不一样?

答:getAttribute 返回原始字符串;.href 是 URL property,会按文档 base 解析成绝对 URL。要原始值用 getAttribute,要可用的绝对地址用 .href。

Q5:cloneNode() 和 outerHTML 复制输入框,有什么区别?

答:outerHTML 只序列化 attribute,看到的是默认值;cloneNode() 对表单控件会复制当前 value/checkedness,看到的是当前状态。

下篇预告

下一卷聊 HTML 表单的默认行为 :<button> 不写 type 为什么会提交表单、Enter 键为什么会隐式提交、formaction / formmethod / formnovalidate 怎么覆盖,以及原生校验到底在什么时候触发。你以为表单只是几个输入框,其实它自带一套提交协议。


参考资料

  1. WHATWG HTML Standard --- Reflecting content attributes in IDL attributes:https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
  2. WHATWG HTML Standard --- HTMLInputElement:https://html.spec.whatwg.org/multipage/input.html#htmlinputelement
  3. WHATWG HTML Standard --- data-* / dataset:https://html.spec.whatwg.org/multipage/dom.html#dom-dataset
  4. MDN --- Element.getAttribute():https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
  5. MDN --- HTMLInputElement.value:https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/value
  6. MDN --- HTMLElement.dataset:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
  7. React --- <input>(受控 / 非受控):https://react.dev/reference/react-dom/components/input
  8. Vue --- Form Input Bindings:https://vuejs.org/guide/essentials/forms.html
相关推荐
Rain的Java大神之路9 分钟前
MySQL 与 Redis 双写一致性:从 Cache-Aside 到 Binlog 兜底,一次讲透
java·后端·面试
泡海椒19 分钟前
Java 生成接口调用量趋势 PDF:jquick-pdf 多重折线图(JChartType.MultipleLine)落地
java·开发语言·pdf
徐小夕29 分钟前
LlamaIndex Memory 深度拆解:为什么持久化记忆才是 Agent 从"玩具"走向"工具"的那一步
前端·vue.js·github
syf06111339 分钟前
Java 多线程编程:从原理到实战
java·开发语言
map_3d_vis1 小时前
百度地图自定义控件与右键菜单 ContextMenu
前端·javascript·地图·百度地图
恋猫de小郭1 小时前
Flutter 奇葩 Bug:错过一次合成,后续每帧的 Raster 都顺带变慢?
android·前端·flutter
狂师1 小时前
推荐一款手机自动化神器:phone-harness
前端·开源·测试
pan_junbiao7 小时前
Go 语言基本数据类型
java·前端·golang
这个昵称不容易11 小时前
网上摄影工作室系统设计与实现:96 个 Java 文件、115 个接口,作品发布到点赞评论一条线走完
java·springboot·毕设