Reputation: 23213
I know that you can associate a label with an input using the for and id attributes. However can you use a class and not an id? Thanks
<label for="rooms">Number of rooms</label>
<select id="rooms">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Upvotes: 30
Views: 29701
Reputation: 31
you can do this :
<label class="col-md-12 input-group input-group-sm">
<span class="col-sm-5 control-label text-nowrap">Code</span>
<input class="form-control listen code" type="text" size="15" required/>
</label>
Upvotes: 3
Reputation: 505
Here is an example of when you wouldn't want to use an ID or nest the control:
I'm creating a BackboneJS application that uses templates. Because the template can be duplicated, it's important to refrain from using IDs, as it will create multiple elements in the DOM with the same ID.
I'm also using Bootstrap, which will present the control in a different (and undesirable) way if it's wrapped inside the <label>
element.
At this point, the only solution I can find is to wrap the control element and tweek the default CSS to get the desired output. If someone has a more elegant solution, please chime in.
Upvotes: 5
Reputation: 175098
Classes are not unique (you can have multiple elements with the same class), so no.
If you want to associate a label to an input without using ID, you can implicitly assign it by including said input inside of the label:
<label>Number of rooms
<select name="rooms">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</label>
Upvotes: 58
Reputation: 19963
No, you cannot use the class
of an element, because the same class can be used by multiple elements - in which case, which element would the label
be for?
Upvotes: 4
Reputation: 944529
No, you can't. The only attribute you can use is the id
attribute.
It doesn't make sense to use a class (which describes a group of related elements) since a label can be associated only with exactly one form control.
Upvotes: 3