Praveen
Praveen

Reputation: 56539

Can I use label for a label tag?

Usually I used label tag for pointing input tag like this

<label for='firstname'>First Name:</label>
<input type='text' id='firstname' />

Now I have this

<label for='firstname'>First Name:</label>
<label id='firstname'></label>

Since I haven't crossed anything like this before, is it possible to have label tag for a label. Will it work, when I apply Javascript because I have to update the values? or this is a valid w3c compliance?

I'm confused whether to use it or not.

Upvotes: 3

Views: 1792

Answers (5)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201886

As others have answered, the label element must refer to a control, such as input, so it must not refer to another label element, even syntactically. This restriction is present even in HTML5.

This means that if you read user input using elements other than controls, you can still use labels for them, but you must not use label markup for the label. Normally, text data like names is best read using input type=text. If you cannot use it, or another control, for some reason, then the approach recommended in ARIA specifications is to a semantically neutral element, normally span, and use the ARIA attribute aria-labelledby to specify the connection between a label and the span. Example:

<span id=firstnameLabel>First Name:</span>
<span role=textbox id=firstname aria-labelledby=firstnameLabel></span>

The ARIA attributes are primarily meant for assistive or otherwise accessibility-aware software. They are probably ignored by mainstream browsers.

Upvotes: 2

maniacalrobot
maniacalrobot

Reputation: 2463

The Label "For" attribute has to point to a valid ID attribute of a "control" element, http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.2 lists valid control elements as buttons, checkboxes, radio buttons, menus, file select, hidden controls, object controls.

It might work in JS, but it would be invalid HTML

Upvotes: 0

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13556

Label for label is non-conforming. Probably HTML5 output element is what you want?

Upvotes: 0

federicot
federicot

Reputation: 12341

It's invalid according to the W3C validator.

The for attribute of the label element must refer to a form control.

Upvotes: 6

Quentin
Quentin

Reputation: 944500

No. Label elements label (primarily) form controls (<input>, <button>, etc), not arbitrary elements.

See the HTML specification:

Some elements, not all of them form-associated, are categorized as labelable elements. These are elements that can be associated with a label element.

button, input (if the type attribute is not in the hidden state), keygen, meter, output, progress, select, textarea

Upvotes: 4

Related Questions