<!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>
当你执行完 content.removeChild(add[i]); content里面的子节点变化了,每次都减少一个,当你删除add[3]元素时,在content里面就找不到add[3]元素,add[3] = undefned
在删掉之前在重新获取一下content里面的子元素