document对象时HTMLDocument的实例,而HTMLDocument又继承自Document类型。
document对象表示整个HTML页面。并且document对象时window对象的一个属性,因此可以作为全局对象来访问。
Document节2点基本特征:
- nodeType:9
- nodeName:#document
- nodeValue:null
- ownerDocument:null
1.文档的子节点
DOM标准规定Document节点的子节点可以时DocumentType、Element、ProcessingInstruction或Comment。但还有两个内置的访问其子节点的快捷方式(属性)。
(1)documentElement,始终指向HTML页面的<html>元素。
(2)childNodes,返回子节点列表。
<!DOCTYPE html>
<!--nihai-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var html = document.documentElement;
console.log("我是:"+html); //我是:[object HTMLHtmlElement]
console.log("我是:"+document.childNodes[2]);//我是:[object HTMLHtmlElement]
console.log(html == document.childNodes[2]);//true
</script>
</body>
</html>
childNodes[2]才是HTMLHtmlElement节点。0是documentType,1是comment。而documentElement只是html元素。
(3)body属性
这是作为HTMLDocument的实例,而有的属性,直接指向<body>元素。document.body在JavaScript开发中经常用到。
所有浏览器都支持document.documentElement和document.body属性。
(4)doctype属性——指向文档类型声明<!DOCTYPE>.(不同浏览器对document.doctype支持差别很大)
使用时要注意浏览器差别。
2.文档信息
(1)document.title:可以获取或设置<title>元素中的文本
var title = document.title; console.log(title); document.title = "wyc要努力"; console.log(document.title);
(2)URL,domain,referrer.
URL:获取页面完整的URL
domain:获取或设置页面的域名。
referrer:获取链接到当前页面的那个页面的URL
console.log(document.URL);
document.domain = "wyc"; //报错:'wyc' is not a suffix of 'localhost'.
console.log(document.domain);
- 只有domain是可以设置的,但不能将domain属性设置为URL中不包含的域。
- 如果页面包含来自其他子域的框架或内框架时,他们之间无法通过javascript通信(由于跨域安全限制)。但是可以设置document.domain为相同的值,来实现通信。
3.查找元素
(1)getElementById():根据id获取元素
(2)getElementsByTagName():根据标签名获取,返回一个HTMLCollection对象(和NodeList相似)。
注:HTMLCollection有一个namedItem()方法,通过元素的name属性获取集合中的第一项。
(3)getElementsByName():只有HTMLDocument类型才有的办法。和getElementsByTagName()类似,返回HTMLCollection对象。
4.特殊集合
document.anchors:包含文档中所有带name特性的<a>元素。
document.forms:包含文档中所有的<form>元素。
document.images:包含文档中所有的<img>元素。
document.links:包含文档中所有带href特性的<a>元素。
5.DOM一致性检测
document.implementation规定了一个方法,hasFeature()。两个参数:要检测DOM功能的名称及版本号。
var hasXmlDom = document.implementation.hasFeature(“XML”,“1.0”);
6.文档写入
write(),writeln(),open()和close().
//输出当前日期和时间——正确
document.write("<strong>"+(new Date()).toString()+"</strong>");
//动态包含外部资源
document.write("<script type=\"text/javascript\" src=\"file.js\">"+"<\/script>");
注意:给</script>加上转义符,这样<\/script>不会被当作外部<script>标签。
<body>
<p>wyc要努力</p>
<script>
//输出当前日期和时间——正确
window.onload = function() {
document.write("<strong>" + (new Date()).toString() + "</strong>");
}
</script>
</body>
如果在文档加载后调用document.write,输出的内容将会重写整个页面。即代码中“wyc要努力”不会显示,只显示日期。