CKTIS / HTML
The HTML for attribute
The `for` attribute has element-specific meanings: it associates a `label` with a control, identifies inputs to an `output`, or connects a `template` to a named processing-instruction marker. It is neither a global attribute nor an instruction to perform a calculation.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
<label for="control-id">…</label>
<output for="input-id-1 input-id-2">…</output>
<template for="marker-name">…</template>The for attribute describes different relationships depending on its element. It is not a global attribute. On label and output, it refers to id values, not name attributes or CSS selectors.
For label, the value is one id identifying a labelable element in the same tree. The first element with the matching id in tree order determines the association, but only if it is labelable. Use unique identifiers. Without for, the label associates with its first labelable descendant; an invalid for does not trigger that fallback.
For output, the value is an unordered set of unique, space-separated IDs. Each must identify an element in the same tree whose value or behavior influenced the result. The attribute does not calculate or update the result itself—the example uses a script for that. In the DOM, label.htmlFor is a string, whereas output.htmlFor exposes a DOMTokenList.
For template, the value identifies a named marker for inserting or replacing content: it must match the name attribute of a <?marker> or <?start> processing instruction in the same tree. This is not an id reference. Do not confuse this mechanism with form labeling; check its behavior in your target browsers before adopting it.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>for attribute</title>
<label for="a">A</label>
<input id="a" type="number" value="2">
<label for="b">B</label>
<input id="b" type="number" value="3">
<output id="sum" for="a b"></output>
<script>
const a = document.getElementById('a');
const b = document.getElementById('b');
const sum = document.getElementById('sum');
function update() {
sum.value = String(a.valueAsNumber + b.valueAsNumber);
}
a.addEventListener('input', update);
b.addEventListener('input', update);
update();
console.log(document.querySelector('label').control === a);
console.log(sum.htmlFor.contains('a'), sum.htmlFor.contains('b'));
console.log(sum.value);
</script>
</html>Result
true true true 5
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.