Hone

Lessons · HTML and CSS · for= and id=, or wrap it

for= and id=, or wrap it

A label is attached by for= pointing at an id=, or by containing the input. Nothing else attaches it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

An attached label is the field's name -- what a screen reader announces -- and it also makes the label clickable, which on a phone is the difference between a checkbox anybody can tick and one only some people can.

How to think about it

Use for=/id= when the two are apart in the markup, and wrapping when they are together. Then ask the browser rather than guessing: input.labels is empty when nothing is attached.

Worked example

<label for="e">Email</label><input id="e">
Attached: the input's .labels has 1 entry.
<label>Email <input id="e"></label>
Also attached, with no ids invented. The label's .control points back at the input.

Your turn

for= points at the input's

The trap

Being next to each other on screen attaches nothing. It looks attached to a sighted reader and is nothing at all to a browser.

Practise for= and id=, or wrap it on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.