Erase options within optgroup

2

I have select with two optgroup . I want in JS to delete all% with% that are only in options .

<select id = "testSelect" name="testSelect">
   <optgroup label="opt1">
      <option value="3">Apples</option>
      <option value="1">Oranges</option>
      <option value="2">Pears</option>
   </optgroup>
   <optgroup label="opt2">
      <option value="4">ford</option>
      <option value="6">toyota</option>
      <option value="5">ferrari</option>
   </optgroup>
</select>

In this example I want to delete the optgroup from options 2. Something like this:

$$("input[type=select][id=^testSelect][label="opt2"]").each(function(curr){
//get outgroup
//remove all options;
}
    
asked by anonymous 25.11.2016 / 12:22

1 answer

2

You can do this to delete everything (including optgroup )

document.querySelector('optgroup[label="opt2"]').remove();
<select name="testSelect">
   <optgroup label="opt1">
      <option value="3">Apples</option>
      <option value="1">Oranges</option>
      <option value="2">Pears</option>
   </optgroup>
   <optgroup label="opt2">
      <option value="4">ford</option>
      <option value="6">toyota</option>
      <option value="5">ferrari</option>
   </optgroup>
</select>

Or use this to delete only options

document.querySelectorAll('optgroup[label="opt2"] option').forEach(function(el) {
    el.remove();
});
    
25.11.2016 / 12:28