I have an HTML <select>
element that contains some <optgroup>
elements containing some <option>
elements, like this:
<select>
<optgroup label="label1">Label 1
<option>opt1.1</option>
<option>opt1.2</option>
<option>opt1.3</option>
</optgroup>
<optgroup label="label2">Label 2
<option>opt2.1</option>
<option>opt2.2</option>
</optgroup>
...
</select>
I would like to hide all <option>
s except the ones in a specific <optgroup>
, and then later show them again if the user wants to (that is: I don't want to use innerHTML = '';
, because I want to be able to restore my <option>
s back later). So I wrote this:
var groups = document.getElementsByTagName('optgroup');
for (var i = 0; i < groups.length; i++) {
if (groups[i].label != str) {
var options = groups[i].childNodes;
for (var j = 0; j < options.length; j++)
options[j].style.display = 'none';
}
}
and it doesn't work (on Firefox and Safari). Even if I try something like options[j].style.color = 'red';
nothing happens. But options[j].disabled = true;
works, although I would like to hide those <options>
s completely.
... why on Earth?
P.S. I can only use vanilla JavaScript :)