← 中文资源

简体中文版本

label 的 htmlFor 关联表单控件

for 属性与包裹写法都能把 label 关联到控件;element.labels 实时反映关联,给 htmlFor 赋新值会立即改指向,无障碍点击命中区域同步生效。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:emailInput、checkbox、label。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。

常见问题

「label 的 htmlFor 关联表单控件」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

<label>Enabled <input id="enabled" type="checkbox" /></label>
</form>
`;
const label = document.querySelector("label[for='email']");
const emailInput = document.querySelector("#email");

代码示例

document.body.innerHTML = `
  <form>
    <label for="email">Work email</label>
    <input id="email" type="email" />
    <label>Enabled <input id="enabled" type="checkbox" /></label>
  </form>
`;

// for attribute associates label and control by id
const emailInput = document.querySelector("#email");
console.log(emailInput.labels.length);          // 1
console.log(emailInput.labels[0].textContent);  // Work email

// Wrapping associates without a for attribute
const checkbox = document.querySelector("#enabled");
console.log(checkbox.labels.length);            // 1

// Assigning htmlFor re-points the association live
const label = document.querySelector("label[for='email']");
label.htmlFor = "enabled";
console.log(emailInput.labels.length);          // 0
console.log(checkbox.labels.length);            // 2