Document节点

Stella981
• 阅读 532

原文地址:https://wangdoc.com/javascript/

概述

document节点对象代表整个文档,每张网页都有自己的document对象。 window.document属性就指向这个对象。只要浏览器开始载入HTML文档,该对象就存在了,可以直接使用。 document对象有不同的办法可以获取。

  • 正常的网页,直接使用documentwindow.document
  • iframe框架里面的网页,使用iframe节点的contentDocument属性。
  • Ajax操作返回的文档,使用XMLHttpRequest对象的responseXML属性。
  • 内部节点的ownerDocument属性。 document对象继承了EventTarget接口,Node接口,ParentNode接口。这意味着这些接口的方法都可以在document对象上调用。除此之外,document对象还有很多自己的属性和方法。

属性

快捷方式属性

以下属性是指向文档内部的某个节点的快捷方式。 (1)document.defaultView document.defaultView属性返回document对象所属的window对象。如果当前文档不属于window对象,该属性返回null

document.defaultView === window // true

(2)document.doctype 对于HTML文档来说,document对象一般有两个子节点。第一个子节点是document.doctype,指向节点,即文档类型(Document Type Declaration,简写DTD)节点。HTML的文档类型节点,一般写成。如果没有声明DTD,该属性返回null

var doctype = document.doctype;
doctype // "<!DOCTYPE html>"
doctype.name // "html"

document.firstChild通常返回这个节点。 (3)document.documentElement document.documentElement属性返回当前文档的根元素节点(root)。他通常是document节点的第二个子节点,紧跟在document.doctype节点后面。HTML网页的该属性,一般是节点。 (4)document.body,document.head document.body属性指向节点,document.head属性指向节点。 这两个属性总是存在的,如果网页源码省略了,浏览器会自动创建。另外,这两个属性是可写的,如果改写它们的值,相当于移除所有子节点。 (5)document.scrollingElement document.scrollingElement属性返回文档的滚动元素。也就是说,当文档整体滚动时,到底是哪个元素在滚动。 标准模式下,该属性返回文档的根元素document.documentElement(即)。兼容模式下,返回的是元素不存在,返回null

document.scrollingElement.scrollingTop = 0; // 页面滚动到浏览器顶部

(6)document.activeElement document.activeElement属性返回获得当前焦点(focus)的DOM元素。通常,这个属性返回的是