html does not equal document.childNode[0]

html does not equal document.childNode[0]

本文关键字:childNode document does not equal html      更新时间:2023-09-26

下面是我的代码。我不知道为什么var html不等于document.childNodes[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>

这是因为您的第一个节点是DOCTYPE声明。

HTML 元素document.childNodes[1]在文档中。

如果你想要的是任何HTML文档中的html元素,这也是document.documentElement哪个更可靠(参见MDN)。

试试这个:

alert(html === document.firstElementChild);