HTML <optgroup> Element
In HTML, the <optgroup> tag is used to group <option> elements within a <select> dropdown list. This allows for better organization and structure of options within a dropdown menu.
How <optgroup> Works:
To create a group of options within a dropdown menu, you first need to use the <optgroup> tag. This tag is always a child of the <select> tag and can contain one or more <option> elements. By using the label attribute, you can give a name or label to the group of options.
Here is an example code of how to use the <optgroup> tag:
<select>
<optgroup label="Fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
</optgroup>
<optgroup label="Vegetables">
<option value="carrot">Carrot</option>
<option value="broccoli">Broccoli</option>
</optgroup>
</select>
In this example, we have two groups within the dropdown menu: "Fruit" and "Vegetables". Each group contains a couple of options.
Main <optgroup> Tag Attributes:
| Attribute | Description |
|---|---|
label |
Sets the label for the group of options |
The <optgroup> tag has only one main attribute, which is the label attribute. This attribute is used to give a name or label to the group of options within the dropdown menu.