Delete options inside optgroup

Asked

Viewed 49 times

2

I have a select with two optgroup. I want JS to erase all options who are alone in one of the optgroup.

<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 options of optgroup 2. Something of this kind:

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

1 answer

2

You can do so to erase everything (including the 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();
});
  • Thanks works. And after deleting add a new option on this opt2?

  • 1

    @akm Ai is already another question, create a new question with your question and send me the link here to help you. OBS.: If the answer worked for your initial question mark it as a solution so that other people with the same doubt can be helped as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.