JS动态添加删除或清空option选择项


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS动态添加删除或清空option选择项</title>

<button onclick="addOption()">添加</button>
<button onclick="delFirst()">删除第一个</button>
<button onclick="delLast()">删除最后一个</button>
<button onclick="setEmpty()">清空</button>
<button onclick="count()">元素个数</button>
<hr>
<select id="mySelect" size="29" style="width:163px;">
<option id="0">1500km.com</option>
<option id="1">blog.1500km.com</option>
<option id="2">hello,1500km</option>
</select>



<script>
var i=3;
function addOption(){
    var v='hello~~~'+i;
    var node=document.createElement("option");
    var x=document.createTextNode(v);
    node.appendChild(x);
    node.setAttribute("id",'iidd');  
    node.setAttribute("name","newOption");  
    document.getElementById("mySelect").appendChild(node);
    i++;
}

function delFirst(){
    var x=document.getElementById("mySelect");
    var a=document.getElementsByTagName("option");
    x.removeChild(a[0]);      
}


function delLast(){
    var x=document.getElementById("mySelect");
    var a=document.getElementsByTagName("option");
    x.removeChild(a[a.length-1]);      
}

function setEmpty(){
    var x=document.getElementById("mySelect");
    var a=document.getElementsByTagName("option");
    for(var i=a.length-1;i>=0;i--){
        x.removeChild(a[i]);      
    }
}


function count(){
    var a=document.getElementsByTagName("option");
    alert(a.length);      
}


</script>



   

程序运行结果如下,点击这里亲自运行看看