zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JavaScript HTML DOM removeChild删除子元素

JavaScriptHTML 删除 元素 dom
2023-09-11 14:21:46 时间

removeChild 方法指定元素的某个指定的子节点,并返回被删除的节点,如果节点不存在则返回 null。

 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        <style>
        *{
        	margin:5px;
        	padding:0;
        }
        #box{
        	border:1px solid blue;
        	width:300px;
        	height:200px;
        }
        
        </style>
        </head>
        <body>
        	<div id="box"></div>
        	
        	<button onclick='add()'>添加元素</button>
        	<button onclick='remove()'>从头删除元素</button>
        	<button onclick='removeTail()'>从尾部删除元素</button>
        	<div id="box1" >
        	</div>
        </body>
<script>
	var i=1;
	var box = document.getElementById("box");
	function add(){
		var p = document.createElement("p");
			p.innerText='这是新的P元素'+(i++);
			
			box.appendChild(p);
   }
  function remove(){
  	if(!box.hasChildNodes()) return ;//如果没有子节点则返回
  	box.removeChild(box.firstChild);
  }
  function removeTail(){
  	if(!box.hasChildNodes()) return ;//如果没有子节点则返回
  	box.removeChild(box.lastChild);
  }
</script>
</html>

效果图: