The label attribute in HTML is to provide a human-readable identifier or title for elements such as <track>, <option>, and <optgroup>.
Definition and Usage
➔ The label attribute is used on various elements, each with a specific purpose:
- In <track> element: label specifies the title of the text track.
- In <option> element: label specifies a shorter, alternative text for the option within a drop-down list, if the main text is too long.
- In <optgroup> element: label specifies a label for a group of related options in a drop-down list.
Syntax
//In HTML
<label id="namelabel" for="name">Name:</label>
<input type="text" id="name">
<label>
Email:
<input type="text" name="email">
</label>
//In JavaScript
<script>
let label = document.querySelector("#namelabel");
let element = document.querySelector("#name");
label.for = element.id;
label.setAttribute('for', element.id);
</script>
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| label | <track>, <optgroup>, <option> |