label htmlFor Associates Form Controls

The for attribute and label wrapping both connect a label to its control; element.labels stays live and htmlFor re-points the association on assignment.

JavascriptForm Validation

Code

javascriptsnippet
22 lines
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

Tracing the program flow

Everything operates on top-level bindings: emailInput, checkbox, label.

Watch out for

  • No third-party code is loaded at any point while this runs.
  • A browser is the runtime here: document are not available in Node.

Statements that matter

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

Interactive Tools for This Topic

FAQ

Does label htmlFor Associates Form Controls run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.