概述
document节点是文档的根节点,每张网页都有自己的document节点。window.document属性就指向这个节点。只要浏览器开始载入HTML文档,这个节点对象就存在了,可以直接调用。
内部节点属性
document.doctype,document.documentElement,document.defaultView
document对象一般有两个子节点。第一个子节点是document.doctype,它是一个对象,包含了当前文档类型(Document Type Declaration,简写DTD)信息
var doctype = document.doctype;
doctype // "<!DOCTYPE html>"
doctype.name // "html"
document.documentElement属性返回当前文档的根节点(root)。
document.defaultView属性,在浏览器中返回document对象所在的window对象,否则返回null。
document.defaultView === window // true
document.body,document.head
document.head属性返回当前文档的<head>节点,document.body属性返回当前文档的<body>。
document.head === document.querySelector('head') // true
document.body === document.querySelector('body') // true
document.activeElement
document.activeElement属性返回当前文档中获得焦点的那个元素。用户通常可以使用Tab键移动焦点,使用空格键激活焦点。比如,如果焦点在一个链接上,此时按一下空格键,就会跳转到该链接。
节点集合属性
document.links,document.forms,document.images,document.embeds
document.links属性返回当前文档所有设定了href属性的a及area元素。
document.forms属性返回页面中所有表单元素form。
var selectForm = document.forms[0];
document.images属性返回页面所有图片元素(即img标签)。
var imglist = document.images;
for(var i = 0; i < imglist.length; i++) {
if (imglist[i].src === 'banner.gif') {
// ...
}
}
document.embeds属性返回网页中所有嵌入对象,即embed标签。
document.scripts,document.styleSheets
document.scripts属性返回当前文档的所有脚本(即script标签)。
var scripts = document.scripts;
if (scripts.length !== 0 ) {
console.log('当前网页有脚本');
}
document.styleSheets属性返回一个类似数组的对象,代表当前网页的所有样式表
文档信息属性
document.documentURI,document.URL
document.documentURI属性和document.URL属性都返回一个字符串,表示当前文档的网址
document.domain
document.domain属性返回当前文档的域名。比如,某张网页的网址是 http://www.example.com/hello.html ,domain属性就等于www.example.com。如果无法获取域名,该属性返回null。
var badDomain = 'www.example.xxx';
if (document.domain === badDomain)
window.close();
document.lastModified
document.lastModified属性返回当前文档最后修改的时间戳,格式为字符串。
document.location
document.location属性返回location对象,提供了当前文档的URL信息。
// 当前网址为 http://user:passwd@www.example.com:4097/path/a.html?x=111#part1
document.location.href // "http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
document.location.protocol // "http:"
document.location.host // "www.example.com:4097"
document.location.hostname // "www.example.com"
document.location.port // "4097"
document.location.pathname // "/path/a.html"
document.location.search // "?x=111"
document.location.hash // "#part1"
document.location.user // "user"
document.location.password // "passwd"
// 跳转到另一个网址
document.location.assign('http://www.google.com')
// 优先从服务器重新加载
document.location.reload(true)
// 优先从本地缓存重新加载(默认值)
document.location.reload(false)
// 跳转到新网址,并将取代掉history对象中的当前记录
document.location.replace('http://www.google.com');
// 将location对象转为字符串,等价于document.location.href
document.location.toString()
如果将新的网址赋值给location对象,网页就会自动跳转到新网址。
document.location = 'http://www.example.com';
// 等同于
document.location.href = 'http://www.example.com';
如果指定的是锚点,浏览器会自动滚动到锚点处。
document.location = '#top';
document.referrer,document.title,document.characterSet
document.referrer属性返回一个字符串,表示当前文档的访问来源,如果是无法获取来源或是用户直接键入网址,而不是从其他网页点击,则返回一个空字符串。
document.title属性返回当前文档的标题,该属性是可写的。
document.title = '新标题';
document.characterSet属性返回渲染当前文档的字符集,比如UTF-8、ISO-8859-1。
document.readyState
document.readyState属性返回当前文档的状态,共有三种可能的值。
loading:加载HTML代码阶段(尚未完成解析)
interactive:加载外部资源阶段时
complete:加载完成时
document.designMode
document.designMode属性控制当前文档是否可编辑,通常用在制作所见即所得编辑器。打开iframe元素包含的文档的designMode属性,就能将其变为一个所见即所得的编辑器。
<iframe id="editor" src="about:blank"></iframe>
<script>
!(function () {
var editor = document.getElementById('editor');
editor.contentDocument.designMode = 'on';
})();
</script>
document.implementation
document.implementation属性返回一个对象,用来甄别当前环境部署了哪些DOM相关接口。implementation属性的hasFeature方法,可以判断当前环境是否部署了特定版本的特定接口。
document.implementation.hasFeature('HTML', '2.0')
// true
document.implementation.hasFeature('MutationEvents','2.0')
// true
document.compatMode
compatMode属性返回浏览器处理文档的模式,可能的值为BackCompat(向后兼容模式)和CSS1Compat(严格模式)。
一般来说,如果网页代码的第一行设置了明确的DOCTYPE(比如<!doctype html>),document.compatMode的值都为CSS1Compat。
document.cookie
document.cookie属性用来操作浏览器Cookie,详见《浏览器环境》一章的《Cookie》部分。
读写相关的方法
document.write(),document.writeln()
document.write方法用于向当前文档写入内容。只要当前文档还没有用close方法关闭,它所写入的内容就会追加在已有内容的后面。
document.writeln方法与write方法完全一致,除了会在输出内容的尾部添加换行符。
document.write(1);
document.write(2);
// 12
document.writeln(1);
document.writeln(2);
查找节点的方法
document.querySelector(),document.querySelectorAll()
document.querySelector方法接受一个CSS选择器作为参数,返回匹配该选择器的元素节点。如果有多个节点满足匹配条件,则返回第一个匹配的节点。如果没有发现匹配的节点,则返回null。
var el1 = document.querySelector('.myclass');
var el2 = document.querySelector('#myParent > [ng-click]');
document.querySelectorAll方法与querySelector用法类似,区别是返回一个NodeList对象,包含所有匹配给定选择器的节点。
document.getElementsByTagName()
document.getElementsByTagName方法返回所有指定HTML标签的元素,返回值是一个类似数组的HTMLCollection对象,可以实时反映HTML文档的变化。如果没有任何匹配的元素,就返回一个空集。
var paras = document.getElementsByTagName('p');
paras instanceof HTMLCollection // true
上面代码返回当前文档的所有p元素节点。
如果传入*,就可以返回文档中所有HTML元素。
var allElements = document.getElementsByTagName('*');
document.getElementsByClassName()
document.getElementsByClassName方法返回一个类似数组的对象(HTMLCollection实例对象),包括了所有class名字符合指定条件的元素,元素的变化实时反映在返回结果中。
var elements = document.getElementsByClassName(names);
document.getElementsByName()
document.getElementsByName方法用于选择拥有name属性的HTML元素(比如<form>、<radio>、<img>、<frame>、<embed>和<object>等),返回一个类似数组的的对象(NodeList对象的实例),因为name属性相同的元素可能不止一个。
// 表单为 <form name="x"></form>
var forms = document.getElementsByName('x');
forms[0].tagName // "FORM"
document.getElementById()
etElementById方法返回匹配指定id属性的元素节点。如果没有发现匹配的节点,则返回null。
var elem = document.getElementById('para1');
document.getElementById方法与document.querySelector方法都能获取元素节点,不同之处是document.querySelector方法的参数使用CSS选择器语法,document.getElementById方法的参数是HTML标签元素的id属性。
document.elementFromPoint()
document.elementFromPoint方法返回位于页面指定位置最上层的Element子节点。
var element = document.elementFromPoint(50, 50);
上面代码选中在(50, 50)这个坐标位置的最上层的那个HTML元素。
elementFromPoint方法的两个参数,依次是相对于当前视口左上角的横坐标和纵坐标,单位是像素。如果位于该位置的HTML元素不可返回(比如文本框的滚动条),则返回它的父元素(比如文本框)。如果坐标值无意义(比如负值或超过视口大小),则返回null。
生成节点的方法
document.createElement()
document.createElement方法用来生成网页元素节点。
var newDiv = document.createElement('div');
document.createTextNode()
document.createTextNode方法用来生成文本节点,参数为所要生成的文本节点的内容。
var newDiv = document.createElement('div');
var newContent = document.createTextNode('Hello');
newDiv.appendChild(newContent);
上面代码新建一个div节点和一个文本节点,然后将文本节点插入div节点。
document.createAttribute()
document.createAttribute方法生成一个新的属性对象节点,并返回它。
attribute = document.createAttribute(name);
createAttribute方法的参数name,是属性的名称。
var node = document.getElementById("div1");
var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
// 等同于
var node = document.getElementById("div1");
node.setAttribute("my_attrib", "newVal");
事件相关的方法
document.createEvent()
document.createEvent方法生成一个事件对象,该对象可以被element.dispatchEvent方法使用,触发指定事件。
var event = document.createEvent(type);
document.addEventListener(),document.removeEventListener(),document.dispatchEvent()
以下三个方法与document节点的事件相关。这些方法都继承自EventTarget接口
// 添加事件监听函数
document.addEventListener('click', listener, false);
// 移除事件监听函数
document.removeEventListener('click', listener, false);
// 触发事件
var event = new Event('click');
document.dispatchEvent(event);
其他方法
document.hasFocus()
document.hasFocus方法返回一个布尔值,表示当前文档之中是否有元素被激活或获得焦点。
var focused = document.hasFocus();
document.createNodeIterator(),document.createTreeWalker()
以下方法用于遍历元素节点。
document.createNodeIterator方法返回一个DOM的子节点遍历器。
var nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_ELEMENT
);
上面代码返回body元素的遍历器。createNodeIterator方法的第一个参数为遍历器的根节点,第二个参数为所要遍历的节点类型,这里指定为元素节点。其他类型还有所有节点(NodeFilter.SHOW_ALL)、文本节点(NodeFilter.SHOW_TEXT)、评论节点(NodeFilter.SHOW_COMMENT)等。
(2)document.createTreeWalker()
document.createTreeWalker方法返回一个DOM的子树遍历器。它与createNodeIterator方法的区别在于,后者只遍历子节点,而它遍历整个子树。
document.createTreeWalker方法的第一个参数,是所要遍历的根节点,第二个参数指定所要遍历的节点类型。
var treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT
);
var nodeList = [];
while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
上面代码遍历body节点下属的所有元素节点,将它们插入nodeList数组。
document.adoptNode()
document.adoptNode方法将某个节点,从其原来所在的文档移除,插入当前文档,并返回插入后的新节点。
node = document.adoptNode(externalNode);
document.importNode()
document.importNode方法从外部文档拷贝指定节点,插入当前文档。
var node = document.importNode(externalNode, deep);
document.importNode方法用于创造一个外部节点的拷贝,然后插入当前文档。它的第一个参数是外部节点,第二个参数是一个布尔值,表示对外部节点是深拷贝还是浅拷贝,默认是浅拷贝(false)。虽然第二个参数是可选的,但是建议总是保留这个参数,并设为true。
注意,importNode方法只是拷贝外部节点,这时该节点的父节点是null。下一步还必须将这个节点插入当前文档的DOM树。
var iframe = document.getElementsByTagName('iframe')[0];
var oldNode = iframe.contentWindow.document.getElementById('myNode');
var newNode = document.importNode(oldNode, true);
document.getElementById("container").appendChild(newNode);
上面代码从iframe窗口,拷贝一个指定节点myNode,插入当前文档。
document.getSelection()
这个方法指向window.getSelection()