本文摘自PHP中文网,作者coldplay.xixi,侵删。
JavaScript删除HTML元素的方法:1、删除节点,代码为【removeChild(oldNode)】;2、删除列表框下拉菜单的选项,代码为【remove(long index)】。

本教程操作环境:windows7系统、javascript1.8.5版,DELL G3电脑。
JavaScript删除HTML元素的方法:
1、删除节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <body id= "test" >
<input id= "add" type= "button" value= "增加" disabled onclick= "add();" />
<input id= "del" type= "button" value= "删除" onclick= "del();" />
<div id= "target" style= "width:240px;height:50px;border:1px solid black" >
被控制的目标元素
</div>
<script>
var body = document.getElementById( "test" );
var target = document.getElementById( "target" );
var add = function (){
body.appendChild(target);
document.getElementById( "add" ).disabled= "disabled" ;
document.getElementById( "del" ).disabled= "" ;
}
var del = function (){
body.removeChild(target);
document.getElementById( "del" ).disabled= "disabled" ;
document.getElementById( "add" ).disabled= "" ;
}
</script>
</body>
|
结果
1

2

2、删除列表框下拉菜单的选项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <body id= "test" >
<input id= "opValue" type= "text" />
<input id= "add" type= "button" value= "增加" onclick= "add();" />
<input id= "del" type= "button" value= "删除" onclick= "del();" />
<select id= "show" size= "8" style= "width:180px" ></select>
<script>
var show = document.getElementById( "show" );
var add = function (){
var op = new Option(document.getElementById( 'opValue' ).value);
show.options[show.options.length] = op;
}
var del = function (){
if (show.options.length>0){
show.remove(show.options.length-1);
}
}
</script>
</body>
|
结果

阅读剩余部分
相关阅读 >>
为什么使用vue的作用域插槽?什么时候使用?
一起看看 鸿蒙 javascript gui 技术栈
浅谈javascript事件模拟
详解js中的执行上下文和执行栈
javascript未知错误怎么查
10个使用console进行javascript调试的高级技巧
js的图片处理与合成详解
javascript如何表示空指针
用javascript获取伪元素(pseudo-element)属性的方法详解
如何用js求圆的面积
更多相关阅读请进入《javascript》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » JavaScript如何删除HTML元素