I am encountering an issue with an HTML <select>
element that contains <optgroup>
elements with <option>
elements nested within them. Here is an example of the structure:
<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 am trying to hide all <option>
elements except the ones within a specific <optgroup>
. I want to maintain the ability to show them again later on, without using innerHTML = '';
. Here is the code I have written for this purpose:
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';
}
}
However, this solution does not seem to work in browsers like Firefox and Safari. Even attempting something simple like changing the color of the options has no effect. Strangely, setting options[j].disabled = true;
works as expected, but I specifically need to fully hide the <option>
elements.
Why might this be happening?
P.S. Please note that I am limited to using vanilla JavaScript only :)