DOM增删操作(select动态增加和删除以及清空)

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<script>
//创建select元素
function createSelect(){
var ele = document.createElement('select');
for(var i=0;i<10;i++){
var op = new Option('NewElment'+i,i);
ele.options[i] = op;
}
ele.size = 1;
ele.id = 'city';
document.getElementById('test').appendChild(ele);
}

//删除元素
function eleremove(){
var city = document.getElementById('city');
if(city.options.length > 0){
//city.remove(city.options.length -1);
city.options[city.options.length -1] = null;
}
}

//清空元素
function clearAll(){
var city = document.getElementById('city');
if(city.options.length > 0){
city.options.length = 0;
}
}

</script>
</head>

<body id="test">
<button value="1" onclick="createSelect()">createSelect</button><br />
<button value="2" onclick="eleremove()">eleremove</button><br />
<button value="3" onclick="clearAll()">clearAll</button>
<hr />
</body>

</html>

posted @ 2017-07-27 16:51  梁大爷  阅读(815)  评论(0编辑  收藏  举报