GFL
GFL

Reputation: 1434

Hide Empty Optgroups

I have some dynamically created select menus, and sometimes there were some optgroups without any options inside.

I hid them with a line of CSS code. It worked in Chrome at the time (2016), but revisiting the website I noticed it's no longer working.

optgroup:empty{display:none}

Is there a way I can tell if it was deprecated? How should I go about hiding optgroup labels if they do not have any options inside?

Upvotes: 0

Views: 1680

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42374

Both the <optgroup> tag and the :empty CSS pseudo-class are supported in all major browsers, and your code will indeed hide empty groups:

optgroup:empty {
  display: none
}
<select>
  <optgroup label="Filled">
    <option value="one">One</option>
    <option value="two">Two</option>
  </optgroup>
  <optgroup label="Empty"></optgroup>
</select>

However, note that when there's a space or newline inside of an element, it is not considered to be empty, as is reported by MDN:

The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments or processing instructions do not affect whether an element is considered empty.

As such, the :empty selector won't target it in the following example:

optgroup:empty {
  display: none
}
<select>
  <optgroup label="Filled">
    <option value="one">One</option>
    <option value="two">Two</option>
  </optgroup>
  <optgroup label="Empty">
  </optgroup>
</select>

In short, to have your empty <optgroup> hidden, you need to make sure that there is absolutely no whitespace between your opening and closing <optgroup> tags.

Upvotes: 7

Related Questions