<optgroup>

Draft

Definition

The <optgroup> HTML element is used to group related options within a <select> element. It provides a way to categorize and organize options into distinct groups.

Here’s an example of how to use the <optgroup> element:

<select>
  <optgroup label="Fruits">
    <option value="apple">Apple</option>
    <option value="orange">Orange</option>
    <option value="banana">Banana</option>
  </optgroup>
  <optgroup label="Vegetables">
    <option value="carrot">Carrot</option>
    <option value="broccoli">Broccoli</option>
    <option value="tomato">Tomato</option>
  </optgroup>
</select>

In this example, the <select> element contains two <optgroup> elements. The first <optgroup> is labeled “Fruits”, and it groups together three fruit options: Apple, Orange, and Banana. The second <optgroup> is labeled “Vegetables”, and it groups together three vegetable options: Carrot, Broccoli, and Tomato.

The label attribute of the <optgroup> element specifies the text to be displayed as the label for the group of options. This label provides a visual clue to users, helping them understand the categorization of the options.

The <optgroup> element is particularly useful when you have a large number of options or want to present a logical grouping of choices to the user. By organizing options into groups, it enhances the readability and usability of the <select> element.

It’s worth noting that not all browsers may support the styling of <optgroup> elements. In some cases, browsers may display the options without any visual grouping or indentation. Therefore, it’s important to consider the browser compatibility and test the appearance of grouped options across different browsers.