唯一合规、语义正确且无障碍友好的html分组方式是标签,它必须直接嵌套在内、有label属性、仅包含、不可选不提交,动态插入须用select.add()而非appendchild()。

用 <optgroup></optgroup> 实现原生分组,别用 class 模拟
HTML 中唯一合规、语义正确、无障碍友好的分组方式,就是 <optgroup></optgroup> 标签。它不是装饰性容器,而是表单规范的一部分,浏览器和读屏软件都依赖它识别逻辑分组。
常见错误包括:把 <optgroup></optgroup> 写在 <select></select> 外面、漏写 label 属性、给 <optgroup></optgroup> 设 value(它没有 value,也不参与提交)。
-
<optgroup></optgroup>必须直接嵌套在<select></select>内,不能包裹在<div> 或其他标签里 <li>每个 <code><optgroup></optgroup>必须有label属性,值会显示为灰色分组标题 -
<optgroup></optgroup>只能包含<option></option>,不能嵌套另一个<optgroup></optgroup> - 分组本身不可选、不提交,只起视觉与语义组织作用
- 创建
<optgroup></optgroup>后,需先设optgroup.label = "xxx",否则 label 不生效 - 往
<optgroup></optgroup>添加<option></option>时,才可用optgroup.appendChild(option) - 不要在循环中反复查 DOM,如
document.getElementById("mySelect")应提前提取变量 -
selected属性是 HTML 属性,写死即生效,无需等待 DOM 渲染完成 - JS 设置
value时,若对应<option></option>尚未插入 DOM,赋值无效且无提示 - 多选
<select multiple></select>场景下,selected属性依然可用,但 JS 需遍历options数组逐个设option.selected = true - 不要给
<optgroup></optgroup>加class并期望通过 CSS 控制外观 - 想高亮某一分组?只能改
label文字内容,或用 JS 动态插入带样式的<option disabled></option>作伪分组标题 - 移动端 Safari 对
<optgroup></optgroup>的渲染最保守,测试务必覆盖
动态插入 <optgroup></optgroup> 时,add() 和 appendChild() 行为不同
JS 创建分组后往 <select></select> 插入,不能直接用 appendChild() —— 浏览器会报错或静默失败。必须用 select.add(optgroup),这是 <select></select> 元素的专有方法。
示例中容易踩坑的是:先用 document.createElement("optgroup") 创建节点,再调用 select.add(optgroup);若误用 select.appendChild(optgroup),Chrome 会抛 DOMException: Failed to execute 'appendChild' on 'Node'。
默认选中项在分组内设置,selected 属性优先于 JS 赋值
静态 HTML 中,直接在某个 <option></option> 上加 selected 属性即可;但若该 <option></option> 在 <optgroup></optgroup> 内,仍完全有效——分组不影响选中逻辑。
JS 动态控制时,select.value = "xxx" 或 select.selectedIndex = n 都能生效,但注意:如果 <select></select> 是空的(比如刚初始化还没 appendChild),这些赋值会被忽略,不会报错,也不会回退。
样式限制多,<optgroup></optgroup> 的 CSS 可控范围很小
浏览器对 <optgroup></optgroup> 的样式支持极弱:color、font-weight 等少数属性在部分浏览器中有效,但 background、padding、border 基本被忽略。Chrome 和 Safari 对 label 文字颜色的支持也不一致。
试图用 optgroup { display: none } 隐藏整个分组?别试——多数浏览器不支持,且破坏语义结构。真要条件显示分组,得用 JS 控制整个 <optgroup></optgroup> 节点的 remove() 或 add()。
<select></select> + <optgroup></optgroup> 就该让位给自定义组件。











