2012-05-04 25 views
0

我想訪問根元素的子節點,但我無法這樣做,因爲返回的元素都是「未定義的」 - 包括返回的數組。如何訪問根元素的子節點?

<html> 
<head> 
    <script> 
     function dothis() 
     { 
     var elements = document.getElementsByTagName("body").parentNode.childNodes; 
     alert(elements.length); 
     } 
    </script> 
</head> 
<body onload="dothis();"> 
    <p>Welcome</p> 
    <ul> 
     <li>hello</li> 
    </ul> 
</body> 

</html>​ 

http://jsfiddle.net/PrPPM/1/

回答

1

getElementsByTagName返回NodeList(根據規範。在某些瀏覽器例如火狐我認爲它返回一個HTMLCollection)。無論如何,它返回的是一個類似數組的對象。您需要訪問特定索引處的元素:

var elements = document.getElementsByTagName("body")[0].parentNode.childNodes;