Document是一种类型,可以表示html文档和xml文档;document是一个表示整个html文档的对象(这个才是最常用的);
document对象是window对象的一个属性,可以直接访问。
这里所有的元素可以理解成标签
文档的子节点
对于html文档,document有且只有一个子节点就是html**元素**
// 返回的是NODE类型还是Element类型呢
var dchild = document.documentElement;
console.log(dchild.nodeName);
console.log(dchild.nodeType);//nodeType=1 证明是NODE类型
var nodeLists = document.childNodes;
console.log('child count:'+nodeLists.length);
var dc1 = nodeLists[0];//该方法是动态的,遍历的时候会存在性能问题
var dc2 = document.firstChild;//第一个节点
console.log('nodeLists[0]:'+dc1.nodeName);
console.log("document.firstChild:"+dc2.nodeName);
7构造器.html:15 HTML
7构造器.html:16 1
7构造器.html:18 child count:1
7构造器.html:21 nodeLists[0]:HTML
7构造器.html:22 document.firstChildHTML
可以看出 document对象只有一个子节点,而且是html元素
document的body属性
body属性可以方便快速获取到body元素(对象)
var body = document.body;
console.log(body.nodeName);//BODY
文档信息
文档信息包括:标题(title),完整的URL,域(domain)
console.log(document.title);
console.log(document.URL);
console.log(document.domain);
通过domain可以让不同的子页面就行跨域通信(相互访问)
查找元素
document可以对整个文档进行操作,最常用就是查找某个或者某组元素(对应node和nodeList对象)
- document.getElementById(“idname”) 根据id名称查找第一次出现的元素
- doucment.getElementsByTagName(“tagname”) 根据元素名称查找所有的元素
如果查询参数为为* **表示查询所有的元素;
<<!DOCTYPE html>
<html>
<head>
<title>jsDemo</title>
</head>
<body>
<div id='bid'></div>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
<script type="text/javascript">
var nodes = document.getElementById('bid');
console.log(nodes.nodeName);
var ntas = document.getElementsByTagName('li');
console.log(ntas.length);
</script>
</script>
</body>
</html>
注意:html中标签是不区分大小写的,但xml不一样
特殊集合
这些特殊集合可以快速访问文档中某些特殊的元素组
- document.anchors 包含所有带name属性的元素
- document.forms 包含所有的表单
- document.images 包含所有
- doucment.links 包含所有带href的
文档写入
- write()
- writeln()
- open()
- close()
<span>write by document</span>
<script type="text/javascript">
document.writeln('now is <strong>'+(new Date()).toString()+"</strong>");
</script>
write by document now is Sat Oct 22 2016 22:06:55 GMT+0800 (中国标准时间)
注意 如果在文档加载完后写入文本会刷新整个页面
<span>write by document</span>
<script type="text/javascript">
document.writeln('now is <strong>'+(new Date()).toString()+"</strong>");
</script>
<script type="text/javascript">
window.onload=function(){
document.writeln('hello world');
};
</script>
hello world