An <label>
element associates a text label with a form <input>
field and is implemented using the DOM HTMLLabelElement
interface. The label can tell users what value should be entered in the input field. Having labels helps the accessibility of a form. You can implicitly or explicitly associate a label with a form. When doing it explicitly, you use the for attribute
, and implicitly, you nest the <input>
directly inside the <label>
.
Attributes
for
-
The value of the
for
attribute must be a singleid
for a labelable form-related element in the same document as the<label>
element. So, any givenlabel
element can be associated with only one form control.Note: To programmatically set the
for
attribute, usehtmlFor
.The first element in the document with an
id
attribute matching the value of thefor
attribute is the labeled control for thislabel
element - if the element with thatid
is actually a labelable element. If it is not a labelable element, then thefor
attribute has no effect. If there are other elements that also match theid
value, later in the document, they are not considered.Multiple
label
elements can be given the same value for theirfor
attribute; doing so causes the associated form control (the form control thatfor
value references) to have multiple labels.Note: A
<label>
element can have both afor
attribute and a contained control element, as long as thefor
attribute points to the contained control element.