ProgrammingMarch 30, 2025 2 minutes read

I using this method to group selection options on the web!

Photo by Pankaj Patel on Unsplash

In web development, we know that the <select> element is often used to show a list of options to users. But when the list of options is super long, it’s better to group those options together to make it easier to navigate. That’s where the <optgroup> element comes in. Previously, do you know what this tag is for? let’s discuss it.

The <optgroup> tag is an HTML element that’s used to group options within a <select> element. By using <optgroup>, you can create a hierarchical structure in the list of options, making it easier for users to find what they’re looking for.

Don’t use this:

<select>
  <option value="" disabled>Fruits</option>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="orange">Orange</option>
  <option value="" disabled>Vegetables</option>
  <option value="carrot">Carrot</option>
  <option value="broccoli">Broccoli</option>
  <option value="artichoke">Artichoke</option>
</select>

Use this:

<select>
  <optgroup label="Fruits">
    <option value="apple">Apple</option>
    <option value="banana">Pisang</option>
    <option value="orange">Orange</option>
  </optgroup>
  <optgroup label="Vegetables">
    <option value="carrot">Carrot</option>
    <option value="broccoli">Broccoli</option>
    <option value="artichoke">Artichoke</option>
  </optgroup>
</select>

In the example above, the options are grouped into two categories, which are “Fruits” and “Vegetables”. Each group has a label displayed above the list of options in that group.

What’s the benefit of using <optgroup>?

  1. Improving Usability: By grouping options, users can easily find what they’re looking for, making their experience better.
  2. Creating a Hierarchical Structure: <optgroup> lets you create a hierarchy in the list of options, so related options can be grouped together.
  3. Enhancing Readability: Grouping options makes the list more structured and easier to read.

So, <optgroup> is a really useful HTML element to group options in a <select> element. By using <optgroup>, you can improve usability, create a hierarchy structure, and enhance the readability of the option list on your website.

Get notifications for new posts

This feature is under development.