js刪除父元素下所有的元素節點程式碼

admin發表於2017-03-24

如果一個父元素下既有元素節點也有文字節點,下面就介紹一下如何刪除此父元素下的所有文字節點。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title> 
<style type="text/css">
body{
  margin:0px;
  padding:0px;
  height:1500px;
}
.top{
  width:50px;
  height:50px;
  background:green;
  position:fixed;
  right:5px;
  bottom:20px;
  display:none;
}
</style> 
<script type="text/javascript">
window.onload=function(){
  var obox=document.getElementById("box");
  var nodes=obox.childNodes;
  for(var index=0;index<nodes.length;index++){
    if(nodes[index].nodeType==1){
      obox.removeChild(nodes[index]);
    }
  }
}
</script>
</head> 
<body> 
<ul id="box">
  螞蟻部落:
  <li>分享互助</li>
  <li>螞蟻部落</li>
  <li>美好明天</li>
</ul>
</body> 
</html>

上面的程式碼實現了我們的要求,首先要獲取box父元素下的所有的子元素節點,然後通過for迴圈遍歷每一個子元素節點,並判斷節點型別是否是元素節點,如果是則刪除此節點,就這麼簡單。

相關文章