首页 > 代码库 > DOM增删操作(select动态增加和删除以及清空)

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="http://www.mamicode.com/1" onclick="createSelect()">createSelect</button><br />
<button value="http://www.mamicode.com/2" onclick="eleremove()">eleremove</button><br />
<button value="http://www.mamicode.com/3" onclick="clearAll()">clearAll</button>
<hr />
</body>

</html>

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