How do you set the for
attribute of an HTML <label>
element in JavaScript, without using jQuery or any other library?
The HTML <label> for Attribute is used to specify the type of form element a label is bound to. Syntax: <label for="element_id"> Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to.
To associate the <label> with an <input> element, you need to give the <input> an id attribute. The <label> then needs a for attribute whose value is the same as the input's id .
Use the htmlFor
attribute. I assume it has a slightly cryptic name because for
is a keyword in JavaScript:
var label = document.createElement('label'); label.htmlFor = 'some-input-id';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With