javascript刪除元素節點removeChild()函式

antzone發表於2017-03-22

本章節介紹利用javascript刪除一個元素節點,原生javascript提供了removeChild()能夠實現此功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
ul li{
  width:150px;
  height:20px;
  line-height:20px;
  list-style:none;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var obt=document.getElementById("bt");
  var obox=document.getElementById("box");
  var lis=obox.children;
  obt.onclick=function(){
    obox.removeChild(lis[1]);
  }
}
</script>
</head>
<body>
<ul id="box">
  <li>螞蟻部落一</li>
  <li>螞蟻部落二</li>
  <li>螞蟻部落三</li>
  <li>螞蟻部落四</li>
</ul>
<input type="button" id="bt" value="檢視效果"/>
</body>
</html>

以上程式碼實現了我們的要求,可以刪除第二個li元素。

相關閱讀:

1.children屬性可以參閱javascript children屬性的用法一章節。

2.js對節點的相關操作可以參閱javascript如何獲取元素的子節點和父節點一章節。 

相關文章