看《JavaScript 高级程序设计》书中有 document.documentElement 这样的用法,看文章内容说是获取 <html/> 元素。不过从来没这么用过,简单写了个程序验证了一下。
演示地址1:http://www.xiaoxiaozi.com/code/dom/domele1.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Script 闭合标签</title>
</head>
<body>
<script type="text/javascript">
var oHtml = document.documentElement;
alert(oHtml.tagName);
</script>
</body>
</html>
看来还真是代表的<html/>元素,那如果我把html标签给去掉返回什么呢?
演示地址2:http://www.xiaoxiaozi.com/code/dom/domele2.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>document.documentElement</title>
</head>
<body>
<script type="text/javascript">
var oHtml = document.documentElement;
alert(oHtml.tagName);
</script>
</body>
咱们再来测试一下,我通过document.getElementsByTagName获取html试试,看看二者到底是不是同一个东西
演示地址3:http://www.xiaoxiaozi.com/code/dom/domele3.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>document.documentElement</title>
</head>
<body>
<script type="text/javascript">
var oHtml = document.documentElement;
var oHtml2 = document.getElementsByTagName('html')[0];
alert(oHtml == oHtml2);
alert(oHtml.tagName);
</script>
</body>
</html>
那么,如果我把html标签再删掉时,oHtml2还能获取到吗?
演示地址4:http://www.xiaoxiaozi.com/code/dom/domele4.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>document.documentElement</title>
</head>
<body>
<script type="text/javascript">
var oHtml = document.documentElement;
var oHtml2 = document.getElementsByTagName('html')[0];
alert(oHtml == oHtml2);
alert(oHtml.tagName);
</script>
</body>
稍微有些不解,这个html标签都没了,为啥还能取到呢?看书中有这么一句话,难道可以解惑?
要访问<html/>元素(你应该明白这是该文件的document元素),你可以使用document的documnetElement特性
作者说应该明白的东西我原来还真不明白,记录一下,有心得就是好事。
Good good study ,day day up!~
学习了
不过既然是获取整个document
不是应该等载入完全再test比较准确?