2013-10-21 48 views
-1

以下是我的代碼。我不知道爲什麼var html不等於document.childNodes [0]。它不斷返回false。任何幫助?html不等於document.childNode [0]

<!DOCTYPE html> 
<html> 
<head> 

    <title></title> 
</head> 
<body> 

</body> 
<script type="text/javascript"> 
    var html = document.documentElement; 
    alert(html === document.childNodes[0]); 
    alert(html === document.firstChild); 
</script> 
</html> 
+0

什麼是你真正的目標是什麼?你通常不做這些測試。 –

+0

我正在學習JS,這是本書中的例子之一。它對我來說沒有意義。 –

回答

3

這是因爲你的第一個節點是DOCTYPE聲明。

文檔中的HTML元素是document.childNodes[1]

這也是document.documentElement這是更可靠的(見the MDN),如果你想要的是html元素在任何HTML文檔。

+0

不總是......如果在DOCTYPE和元素之間有註釋,document.childNodes [1]'不會輸出期望值。 –

+0

是的,因爲這個案例沒有任何評論,所以它的作品! –

2

試試這個:

alert(html === document.firstElementChild);