HTML <optgroup> id Attribute

The id attribute on an <optgroup> tag assigns an identifier to the option group element. The identifier must be unique across the page.

Example

#

An id attribute on 2 <optgroup> tags.

<select>
  <option value="">-- Select city -- </option>
  <optgroup id="european-cities" label="Europe">
    <option value="stockholm">Stockholm</option>
    <option value="barcelona">Barcelona</option>
    <option value="athens">Athens</option>
  </optgroup>
  <optgroup id="asian-cities" label="Asia">
    <option value="bangkok">Bangkok</option>
    <option value="manila">Manila</option>
    <option value="jakarta">Jakarta</option>
  </optgroup>
</select>

Using id

The id attribute assigns an identifier to the <optgroup> element.

The identifier must be unique across the page.

The id allows programmatic access to the <optgroup> element.

Tip:  id is a global attribute that can be applied to any HTML element.


Syntax

<optgroup id="identifier" />

Values

#

Value Description
identifier A unique alphanumeric string. The id value must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).

More Examples

An <optgroup> tag with a unique id.
Clicking the button displays the number of <option> elements inside the option group.


<select>
  <option value="">-- Select city -- </option>
  <optgroup id="myoptgroup" label="Europe">
    <option value="stockholm">Stockholm</option>
    <option value="barcelona">Barcelona</option>
    <option value="athens">Athens</option>
  </optgroup>
</select>

<br/>
<button onclick="show();">Show # options</button>

<script>
  let show = () => {
    let element = document.getElementById("myoptgroup");
    let itemCount = element.getElementsByTagName("option").length;
    alert("Option count = " + itemCount);
  }
</script>

Code explanation

The id attribute assigns a unique identifier for the <optgroup>.

Clicking the button calls JavaScript which locates the <optgroup> through the id.

Then counts the number of <option> tag inside the <optgroup> and displays it in an alert box.


Browser support

Here is when id support started for each browser:

Chrome
1.0 Sep 2008
Firefox
1.0 Sep 2002
IE/Edge
1.0 Aug 1995
Opera
1.0 Jan 2006
Safari
1.0 Jan 2003

You may also like

 Back to <optgroup>
Guides