<!DOCTYPE?HTML>
<html>
<head>
<meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8">
<title>刪除節點removeChild()</title>
????????<style?type="text/css">?button?{?cursor:?pointer;?}?</style>
</head>
<body>
<div?id="content">
<h1>html</h1>
<h1>php</h1>
<h1>javascript</h1>
<h1>jquery</h1>
<h1>java</h1>
</div>
<script?type="text/javascript">
var?content?=?document.getElementById("content");
var?add?=?content.childNodes;
alert("當前DIV節點數量為:"?+?add.length);
for(var?i?=?0;?i?<?add.length;?i++)?{
if(add[i].nodeType?!=?1)?{
content.removeChild(add[i]);
};
};
alert("開始清理空白無效節點...");
alert("進度:10%");
alert("進度:25%");
alert("進度:75%");
alert("進度:100%");
alert("當前DIV有效節點數量為:"?+?add.length);
//alert(add.length);
function?detectionText()?{
//?在此完成該函數
for(var?i?=?0;?i?<?add.length;?i++)?{
if(add[i].nodeType?==?1)?{
add[i].style.color?=?"green";
add[i].setAttribute("title",?"節點正常");
};
};
//alert(add.length);
};
function?clearText()?{
for(var?i?=?0;?i?<?add.length;?i++)?{
if(add[i].nodeType?!=?1){
continue;?
}else{
content.removeChild(add[i]);
};
};
};
function?clearoneText()?{
if(add[0].nodeType?==?1)?{
content.removeChild(add[0]);
};
};
function?lengthText()?{
alert("當前DIV有效節點數量為:"?+?add.length);
};
</script>
<button?onclick="detectionText()">檢測節點內容</button>
????????<button?onclick="clearText()">刪除所有節點內容</button>
????????<button?onclick="clearoneText()">刪除第一個節點內容</button>
????????<button?onclick="lengthText()">打印節點長度</button>
????????<br?/><br?/>
<span>點擊檢測按鈕后,字體為綠色則為正常節點,鼠標移動到元素上查看是否為有效節點</span>
</body>
</html>
2018-07-05
當你執行完? content.removeChild(add[i]);??content里面的子節點變化了,每次都減少一個,當你刪除add[3]元素時,在content里面就找不到add[3]元素,add[3] = undefned
2018-07-09
在刪掉之前在重新獲取一下content里面的子元素