日期:2014-05-16  浏览次数:20399 次

为什么取不到子节点
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <script language="javascript">
  var s=document.getElementById("main").childNodes;
  alert(s.length);
  </script>
 </head>

 <body>
 <div id="main"><div id="div1">1231</div></div>
  
 </body>
</html>


------解决方案--------------------
操作dom需要dom加载完毕才可以进行操作


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
<script language="javascript">
window.onload = function(){
var s=document.getElementById("main").childNodes;
alert(s.length);
}
</script>
 </head>

 <body>
 <div id="main"><div id="div1">1231</div></div>
 
 </body>
</html>


或者



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>

 </head>

 <body>
 <div id="main"><div id="div1">1231</div></div>
<script language="javascript">
var s=document.getElementById("main").childNodes;
alert(s.length);
</script>
 </body>
</html>