Dofactory.com
Dofactory.com

HTML <optgroup> data-* Attribute

A data-* attribute on an <optgroup> tag attaches additional data to the option group element.

To create a custom attribute, replace * with a lowercase string, such as data-id, data-status, or data-location.

Example

#

A custom data-price attribute on an <optgroup>.
The attribute value is not visible, but it is readable by JavaScript.

<select>
  <option value="">-- Select color -- </option>
  <optgroup label="One Color" data-price="+$5.00">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
  </optgroup>
  <optgroup label="Two Colors" data-price="+$8.20">
    <option value="red and blue">Red and Blue</option>
    <option value="black and yellow">Black and Yellow</option>
    <option value="blacka and red">Black and Red</option>
  </optgroup>
</select>

Using data-*

The data-* attribute adds custom information to an <optgroup> element.

The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.

An <optgroup> element can have any number of data-* attributes, each with their own name.

Using data-* attributes reduces the need for requests to the server.

Note: The data-* attribute is not visible and does not change the appearance of the optgroup.


Syntax

<optgroup data-*="value">

Note: The * can be any string, such as data-iddata-costdata-supplier,  etc.


Values

#

Value Description
value A string value. Can be numeric, alphanumeric, JSON, etc.

More Examples

A custom data-content attribute on an <optgroup> tag.
Clicking the button will display the content value.


<select>
  <option value="">-- Select color -- </option>
  <optgroup id="myoptgroup" label="Primary Colors" data-content="Colors">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
  </optgroup>
</select>

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

<script>
  let show = () => {
    let element = document.getElementById("myoptgroup");
    alert("Content = " + element.getAttribute('data-content'));
  }
</script>

Code explanation

The <optgroup> tag has a custom data-content attribute.

The data-content attribute stores the content of the option group.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the <optgroup> content.

Note: Notice how the price displays immediately without server call.


Browser support

Here is when data-* 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>

Author: Jack Poorte
Published: Jun 20 2021
Last Reviewed: Sep 30 2023


What's your favorite/least favorite part of Dofactory?


Guides