<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> </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"> function clearText() { var content=document.getElementById("content"); // 在此完成该函数 var o = document.getElementsByTagName('h1'); var i=0 for(i = 0; i<o.length; i--){ content.removeChild(content.childNodes[i]); } } </script> <button onclick="clearText()">清除节点内容</button> </body> </html>
为什么我这是点两下才删除一个节点呢,哪位大神帮忙解答下
childNodes不只是h1等node节点还有你标签的换行回车等文本节点.如果只想删除node节点.建议替换为content.children[i],或者在循环时判断其nodeType==1
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> </head> <body> <div id="content"> <h1>html</h1> <h1>php</h1> <h1>javascript</h1> <h1>jquery</h1> <h1>java</h1> </div> <button onclick="clearText()">清除节点内容</button> <script type="text/javascript"> function clearText() { var content=document.getElementById("content"); // 在此完成该函数 var a = content.childNodes.length; for(var i = 0; i<a; i++){ content.removeChild(content.childNodes[0]); } } </script> </body> </html>