Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Label "FOR" can only refer "ID"?

Tags:

html

jquery-ui

Ok I have a Html element like this

<input type="button" id="harhar"/><label for="harhar">Im only for Id</label>

Is it possible that i can refer a label to a element not using id but a class? like this one

<input type="button" class="harhar"/><label for="harhar">Refer me as a class</label>

is this possible?

NOTE: this is for the sake of creating dynamic Jquery UI buttons in the server-side, that is why I want this to refer a class

like image 793
Netorica Avatar asked Nov 30 '25 16:11

Netorica


2 Answers

No, it is not possible to match a class and a for together. However, there are things that you can do to ensure that your id's and for's are uniquely different from other for and id attributes.

When you generate your elements on the server-side, use a for loop or some other looping construct to enumerate your id/for attributes.

<input type="button" id="harhar_1"/><label for="harhar_1">Im only for Id</label>
<input type="button" id="harhar_2"/><label for="harhar_2">Im only for Id</label>
<input type="button" id="harhar_3"/><label for="harhar_3">Im only for Id</label>

If you can generate your HTML as such, then you'll be able to match up your labels and values while still using unique ids.

Additionally, there is nothing preventing you from still applying a common classname to all of your elements so that you can still easily refer to them with CSS or selectors:

<input class="harhar" type="button" id="harhar_1"/><label for="harhar_1">Im only for Id</label>
<input class="harhar" type="button" id="harhar_2"/><label for="harhar_2">Im only for Id</label>
<input class="harhar" type="button" id="harhar_3"/><label for="harhar_3">Im only for Id</label>

This provides you with the hooks that you need to write succinct CSS rules or manipulate the DOM quickly and easily.

like image 161
jmort253 Avatar answered Dec 02 '25 05:12

jmort253


No, a label always refers to an ID, because only ID is required to be unique in the document, which is exactly what a label needs.

You will have to fall back to creating buttons with predictable, if dynamic, IDs.

like image 36
David Hedlund Avatar answered Dec 02 '25 05:12

David Hedlund