HTML <optgroup> Element

Publish in HTML Tutorial el 25/05/2025 14:12

The <optgroup> HTML element creates a grouping of options within a <select> dropdown menu. It provides a way to organize related options under a common label, making long dropdown lists more user-friendly and easier to navigate.


Key characteristics:

  • Must be used inside a <select> element
  • Contains one or more <option> elements
  • Has a label attribute that displays as a non-selectable heading
  • Improves accessibility by semantically grouping related options


Basic Syntax


Rendered Example

Play Code


Examples

1. Basic Grouping

A simple example grouping countries by continents:

Play Code


2. Disabled Option Group

Showing how to disable an entire group of options:

Play Code


3. Nested Styling (with JavaScript)

Using JavaScript to style options based on their group:

Play Code


4. Dynamic Group Creation (JavaScript)

Creating option groups dynamically with JavaScript:

Play Code


5. Multiple Select with Groups

Using optgroup with a multiple selection dropdown:

Play Code


Tips and Tricks

  • Accessibility: Always include meaningful labels for your optgroups to help screen reader users.
  • Styling: While you can style the <option> elements, browser support for styling <optgroup> labels is limited.
  • Performance: For very long lists, consider dynamically loading optgroups based on user interaction.
  • Mobile: Test your grouped selects on mobile devices as the rendering might differ from desktop browsers.
  • Fallback: If you need complex styling, consider using a custom dropdown component that mimics select/optgroup behavior.

También te puede interesar

HTML <style> Element
HTML <style> Element

The <style> HTML element contains style information for a document, or part of a document. ...

HTML <strong> Element
HTML <strong> Element

The <strong> element is used to indicate that its content has strong importance, seriousnes...

HTML <span> Element
HTML <span> Element

The <span> element is an inline container used to mark up a part of a text or document. Unl...

HTML <source> Element
HTML <source> Element

The <source> element is used to specify multiple media resources for media elements like &l...

HTML <small> Element
HTML <small> Element

The <small> element is used to represent side-comments and small print, typically for discl...

HTML <section> Element
HTML <section> Element

HTML <section> Element: The Complete Guide The <section> element is a semantic HTML ...