J.T. Houtenbos
J.T. Houtenbos

Reputation: 956

Label for input inside other label - is this correct

This is best illustrated with an example:

<label for="myInput">This is an external label</label>

<br>

<label>
This label is wrapped arround the input
<input type="text" id="myInput">
</label>

Is this correct in HTML5? I understand multiple labels can point at one input field, but a label can only point at one field. In the example it are two labels pointing at the same input, only one is wrapping around the input.

Upvotes: 0

Views: 894

Answers (1)

Abhitalks
Abhitalks

Reputation: 28387

Is this correct in HTML5?

Yes.

I understand multiple labels can point at one input field, but a label can only point at one field

Yes, again.

From the specs here: https://www.w3.org/TR/html5/forms.html#the-label-element

The caption can be associated with a specific form control, known as the label element's labeled control, either using the for attribute, or by putting the form control inside the label element itself.

When there is no for attribute and the label is nested with its labelable control, then the first such descendant becomes its labelable control. But, a label should not be nested with other labels.

The label.control property returns the form control that is associated with this element. Vice-versa, .labels is a readonly property on labelable controls which return a nodelist of all applicable labels on that control.

Example 1:

In the example below, the input.labels property returns a nodeList which contains both the labels.

var inp = document.getElementById('myInput');
console.log(inp.labels);
<label for="myInput">This is an external label</label>
<br>
<label>
  This label is wrapped around 
  <input type="text" id="myInput">
</label>


Example 2:

In this example, I have purposefully associated one label to two inputs. See that only the first one encountered i.e. with the for attribute here gets associated, and the second one is ignored even though it has a nested control.

var myInput = document.getElementById('myInput'), 
    yourInput = document.getElementById('yourInput')
;
console.log(myInput.labels);
console.log(yourInput.labels);
<label for="myInput">
	This is an external label
	<input id="yourInput">
</label>
<br>
<input type="text" id="myInput">

Upvotes: 1

Related Questions