<div id="content"> <h1>html</h1> <h1>php</h1> <h1>javascript</h1> <h1>jquery</h1> <h1>java</h1> </div>
1. 删除该节点的内容,先要获取子节点。
2. 然后使用循环遍历每个子节点。
3. 使用removeChild()删除节点。
问题在于循环遍历时习惯性的用了下面这样的办法
function clearText() { var content=document.getElementById("content"); // 在此完成该函数 for(var i=0;i<content.childNodes.length;i++) { content.removeChild(content.childNodes[i]); } }
结果是无法删除干净的,会剩下php 和jqurey
原因是在遍历时因为删除了子节点,content.childNdes.length值已经减小,影响了遍历结果。
合适的循环遍历办法应该是
function clearText() { var content=document.getElementById("content"); for(var i=content.childNodes.length-1;i>=0;i--){ content.removeChild(content.childNodes[i]); } }