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.
Code
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); // 2Tracing 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:
documentare 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.