<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div id="wrap"> <p id="p">测试</p> <div id="div1"> <p><span id="span">文字</span></p> </div> <div id="div2"></div> <!--注释--> <a href="">链接</a> </div> </body> </html> <script> var wrap = document.getElementById("wrap"); var div1 = document.getElementById("div1"); var div2 = document.getElementById("div2"); var a = document.getElementById("a"); var p = document.getElementById("p"); var span = document.getElementById("span"); //找子节点个数 function getChild(obj){ var arr=[]; for(var i=0;i<obj.childNodes.length;i++){ if(!(obj.childNodes[i].nodeType==3 && obj.childNodes[i].nodeValue.trim()=="")){ arr.push(obj.childNodes[i]); } } return arr; } alert(getChild(wrap).length); //找第一个子节点 function getFirstChild(obj){ var firstchild=obj.firstChild; while(firstchild.nodeType==3 && firstchild.nodeValue.trim()==""){ firstchild=firstchild.nextSibling; } return firstchild; } alert(getFirstChild(wrap).nodeName); //找最后一个子节点 function getLastChild(obj){ var lastchild=obj.lastChild; while(lastchild.nodeType==3 && lastchild.nodeValue.trim()==""){ lastchild=lastchild.previousSibling; } return lastchild; } alert(getLastChild(wrap).nodeName); </script>
时间: 2024-10-09 17:32:36