user3412808
user3412808

Reputation: 31

Can I put a span and an input inside a label?

I am building a large form with a dynamic number of fields and I don't want to do this:

<label for="foo">Text</label><input id="foo">

Normally I would do it but I don't want to fumble with foo's 1-50 as well as incrementing more programatically when the user adds a new row. I read that instead of using for attributes, it is perfectly valid to associate a label with a control implicitly by wrapping the label around the control as long as you only have one control in the label. i.e.:

<label>Text<input></label>

However, I would also like to do a little more styling than this allows.

So can I do this?

<label><span>Text</span><input></label>

Or is that invalid markup?

Upvotes: 2

Views: 12183

Answers (2)

Pete
Pete

Reputation: 1305

Expanding on melancia's comment. The MDN label documentation indicates the label element can contain "phrasing content" excluding additional labels. This includes spans.

Upvotes: 2

anam
anam

Reputation: 216

document type does not allow element "LABEL" here; missing one of "P", "H1", "H2", "H3", "H4", "H5", "H6", "PRE", "DIV", "ADDRESS" start-tag.

The mentioned element is not allowed to appear in the context in which you've placed it; the other mentioned elements are the only ones that are both allowed there and can contain the element mentioned. This might mean that you need a containing element, or possibly that you've forgotten to close a previous element.

One possible cause for this message is that you have attempted to put a block-level element (such as "< p >" or "< table >") inside an inline element (such as "< a >", "< span >", or "< font >").

Upvotes: -1

Related Questions