Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

JavaScript - how to remove `options` by its `value`

I have a dropdown menu with products similiar like this

<select class="fruits" >
  <option value="1" >Oranges</option> 
  <option value="2" >Bananes</option> 
  <option value="3" >Apples</option> 
</select>

I need to remove options by its value. How to do that ?
Pure JavaScript please.

EDIT : I know that I need to use element.removeChild(child) method. But how to reference child by its value. Thats my point.

EDIT 2 : I use the script of zdrohn below and it works. Because I have several fruits dropdowns with the same collection I need to iterate trough all dropdowns and delete it from all dropdowns. This is my code now :

<script type='text/javascript'>

var id = 3;
            var el= document.getElementsByClassName("fruits");
                for (i=0;i<el.length;i++) {
                    for(var n = 0; n < el[i].length; n++) {
                        if(el[i][n].value == id) {
                            el[i][n].remove();
                        }
                }

 </script>

Though it works I wonder about that I do not need to use the parent.removeChild() method. How comes ?

P.S. I wonder that peole vote this question down. As the response shows their are several solutions. Though not all are sufficiantly explained.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a snippet to play with.

The code removes the option with value = 3

window.onload = function() {
  var optionToDelete = document.querySelector("select.fruits > option[value='3']");
  optionToDelete.parentNode.removeChild(optionToDelete);
}
<select class="fruits">
  <option value="1">Oranges</option>
  <option value="2">Bananes</option>
  <option value="3">Apples</option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...