# An “optgroup” element with no child “legend” element must have a “label” attribute.

> Canonical HTML version: https://rocketvalidator.com/html-validation/an-optgroup-element-with-no-child-legend-element-must-have-a-label-attribute
> Attribution: Rocket Validator (https://rocketvalidator.com)
> License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/)

Every `<optgroup>` needs a name: give it a `label` attribute, or make a `<legend>` element its first child.

Browsers show the group name as a heading above the group's options, and screen readers announce it when the user moves into the group. The HTML specification requires the `label` attribute whenever the `<optgroup>` has no child `<legend>`. Without either one, the options sit under a blank heading and screen readers have nothing to announce.

Use the `label` attribute unless you have a reason not to. Every browser supports it. The validator only checks that the attribute exists, so `label=""` passes even though the group still has no name. Write the real group name.

The `<legend>` child comes from customizable select, a recent addition to HTML that lets you mark up and style the group heading. Browsers without customizable select support ignore the `<legend>` tag and show the group without a name. Older versions of the W3C validator reject it as well: they report the `<legend>` as a stray start tag and still ask for `label`. If you use a `<legend>`, keep the `label` attribute too. Browsers that support customizable select take the name from the `<legend>`, and older ones fall back to the attribute.

## Invalid example

```html
<label for="car">Car</label>
<select id="car" name="car">
  <optgroup>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup>
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
  </optgroup>
</select>
```

## Valid example

```html
<label for="car">Car</label>
<select id="car" name="car">
  <optgroup label="Swedish cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German cars">
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
  </optgroup>
</select>
```

## Valid example with a legend

```html
<label for="car">Car</label>
<select id="car" name="car">
  <optgroup label="Swedish cars">
    <legend>Swedish cars</legend>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
</select>
```
