How to remove all option inside select using JS loop?

  • 0
    How to remove from select all options whose value is 1, 2 or 3?

    <select id="delete">
      <option value="1">1</option>
      <option value="1">1</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="2">2</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="3">3</option>
      <option value="3">3</option>
      <option value="3">3</option>
    </select>
    JavaScript Anonymous, Apr 12, 2020

  • 3 Answers
  • 0
    Found the answer myself.

    for(let i of document.querySelectorAll("select")) {
    for(let n of i.querySelectorAll("option")) {
    if(n.getAttribute("value") == 1) {
    n.remove();
    } else if(n.getAttribute("value") == 2) {
    n.remove();
    } else if(n.getAttribute("value") == 3) {
    n.remove();
    }
    }
    }
    Anonymous

  • 0
    It is possible to bypass all children of the select tag. It is better to work around from the end, because the result of children is an array-like thing that is updated automatically. If we loop forward through the indices and delete, then we start to skip. Alternatively, go forward, but do not increment the index after deletion. Or decrement, so that on the next iteration the increment returns as it was. Or, in advance, with something like Array.prototype.slice.call, turn an array-like children into a real array, and then work with this inanimate snapshot.
    Anonymous

  • 0
    const values = [ '1', '2', '3' ];
    document.querySelectorAll('option').forEach(n => values.includes(n.value) && n.remove());
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!