Document

Каждая веб-страница, которая загружается в браузер, имеет свой собственный объект document. Интерфейс документа служит точкой входа для получения содержимого веб-страницы (всего DOM (en-US) - дерева, включая такие элементы как <body> и <table> (en-US)), а также обеспечивает функциональность, которая является глобальной для документа, например, для получения URL-адреса страницы или создания новых элементов в документе).

Объект document может быть получен из разных API:

  • Чаще всего используется прямой доступ к объекту document из сценариев scripts (en-US) которые подгружаются документом. (Этот же объект доступен как window.document.)
  • Через свойство contentDocument (en-US) объекта iframe.
  • Как ответ responseXML объекта XMLHttpRequest.
  • Доступ к документу может быть получен из элемента или узла через свойство ownerDocument.

В зависимости от вида документа (т.е. HTML или XML (en-US)) у объекта document могут быть доступны разные API.

  • Все объекты документов реализуют интерфейс Document (и следовательно Node и EventTarget интерфейсы). Таким образом основные свойства и методы, описанные на этой странице, доступны для всех видов документов.
  • В современных браузерах некоторые документы (т.е. те, которые содержат контент text/html) также реализуют HTMLDocument интерфейс.
  • В современных браузерах SVG документы реализуют SVGDocument интерфейс.

В будущем все эти интерфейсы будут сведены в один интерфейс - Document.

Свойства

Примечание: Интерфейс Document наследует также интерфейсы Node и EventTarget.

Document.all Устарело Non-standard

Обеспечивает доступ ко всем элементам с идентификаторами (id). Это нестандартный интерфейс, вместо него рекомендуется использовать метод Document.getElementById().

Document.async Устарело

Используется с document.load чтобы обозначить асинхронный запрос.

Document.characterSet Экспериментальная возможность

Возвращает кодировку документа.

Document.compatMode Экспериментальная возможность

Указывает в каком режиме (Quirks или Strict) рендерился документ.

Document.contentType Экспериментальная возможность

Возвращает Content-Type из MIME заголовка текущего документа.

Document.doctype

Возвращает Document Type Definition (DTD) текущего документа .

Document.documentElement

Возвращает Element, который является первым дочерним элементом документа. Для HTML документов это HTML-элемент.

Document.documentURI

Возвращает URL документа.

Document.domConfig Устарело

Должен вернуть DOMConfiguration объект.

Document.implementation (en-US)

Возвращает DOM implementation связанную с текущим документом.

Document.inputEncoding (en-US) Устарело

Возвращает кодировку, которая использовалась во время парсинга документа.

Document.lastStyleSheetSet (en-US)

Возвращает имя последнего включённого набора таблиц стилей. Имеет значение null , пока таблица стилей не будет изменена путём установки значения selectedStyleSheetSet (en-US).

Document.mozSyntheticDocument (en-US) Non-standard

true если этот документ является синтетическим, например, отдельные изображения, видео, аудио файлы, или тому подобные.

Document.mozFullScreen (en-US) Non-standard

true когда документ находится в full-screen mode.

Document.mozFullScreenElement (en-US) Non-standard

Элемент, который в данный момент находится в полноэкранном режиме для этого документа.

Document.mozFullScreenEnabled (en-US) Non-standard

true if calling element.mozRequestFullscreen() (en-US) would succeed in the curent document.

Document.pointerLockElement (en-US) Экспериментальная возможность

Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.

Document.preferredStyleSheetSet (en-US)

Returns the preferred style sheet set as specified by the page author.

Document.selectedStyleSheetSet (en-US)

Returns which style sheet set is currently in use.

Document.styleSheets (en-US)

Returns a list of the style sheet objects on the current document.

Document.styleSheetSets (en-US)

Returns a list of the style sheet sets available on the document.

Document.xmlEncoding (en-US) Устарело

Returns the encoding as determined by the XML declaration.

Document.xmlStandalone Устарело

Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.

Document.xmlVersion (en-US) Устарело

Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.

The Document interface is extended with the ParentNode interface:

Extension for HTML documents

The Document interface for HTML documents inherit from the HTMLDocument interface or, since HTML5, is extended for such documents:

Document.activeElement

Returns the currently focused element.

Document.alinkColor Устарело

Returns or sets the color of active links in the document body.

Document.anchors

Returns a list of all of the anchors in the document.

Document.applets Устарело

Returns an ordered list of the applets within a document.

Document.bgColor Устарело

Gets/sets the background color of the current document.

Document.body

Returns the <body> element of the current document.

Document.cookie

Returns a semicolon-separated list of the cookies for that document or sets a single cookie.

Document.defaultView

Returns a reference to the window object.

Document.designMode

Gets/sets the ability to edit the whole document.

Document.dir

Gets/sets directionality (rtl/ltr) of the document.

Document.domain

Returns the domain of the current document.

Document.embeds

Returns a list of the embedded <embed> elements within the current document.

Document.fgColor (en-US) Устарело

Gets/sets the foreground color, or text color, of the current document.

Document.forms

Returns a list of the <form> elements within the current document.

Document.head

Returns the <head> element of the current document.

Document.height (en-US) Non-standard

Gets/sets the height of the current document.

Document.images

Returns a list of the images in the current document.

Document.lastModified (en-US)

Returns the date on which the document was last modified.

Document.linkColor (en-US) Устарело

Gets/sets the color of hyperlinks in the document.

Returns a list of all the hyperlinks in the document.

Document.location

Returns the URI of the current document.

Document.plugins (en-US)

Returns a list of the available plugins.

Document.readyState

Returns loading status of the document.

Document.referrer

Returns the URI of the page that linked to this page.

Document.scripts

Returns all the <script> elements on the document.

Document.title (en-US)

Returns the title of the current document.

Document.URL

Returns a string containing the URL of the current document.

Document.vlinkColor (en-US) Устарело

Gets/sets the color of visited hyperlinks.

Document.width (en-US) Non-standard

Returns the width of the current document.

Event handlers

Document.onpointerlockchange Экспериментальная возможность

Returns the event handling code for the pointerlockchange (en-US) event.

Document.onpointerlockerror Экспериментальная возможность

Returns the event handling code for the pointerlockerror (en-US) event.

Document.onreadystatechange

Returns the event handling code for the readystatechange event.

Methods

Примечание: The Document interface also inherits from the Node and EventTarget interfaces.

Document.adoptNode(Node node) (en-US)

Adopt node from an external document.

Document.captureEvents(String eventName) Устарело

See window.captureEvents (en-US).

Document.caretPositionFromPoint(Number x, Number y) (en-US)

Gets a CaretPosition (en-US) based on two coordinates.

Document.createAttribute(String name)

Creates a new Attr object and returns it.

Document.createAttributeNS(String namespace, String name) (en-US)

Creates a new attribute node in a given namespace and returns it.

Document.createCDATASection(String data) (en-US)

Creates a new CDATA node and returns it.

Document.createComment(String comment)

Creates a new comment node and returns it.

Document.createDocumentFragment()

Creates a new document fragment.

Document.createElement(String name)

Creates a new element with the given tag name.

Document.createElementNS(String namespace, String name) (en-US)

Creates a new element with the given tag name and namespace URI.

Document.createEntityReference(String name) (en-US)

Creates a new entity reference object and returns it.

Document.createEvent(String interface) (en-US)

Creates an event object.

Document.createNodeIterator(Node root[, Number whatToShow[, NodeFilter filter]]) (en-US)

Creates a NodeIterator (en-US) object.

Document.createProcessingInstruction(String target, String data) (en-US)

Creates a new ProcessingInstruction (en-US) object.

Document.createRange()

Creates a Range object.

Document.createTextNode(String text)

Creates a text node.

Document.createTreeWalker(Node root[, Number whatToShow[, NodeFilter filter]])

Creates a TreeWalker (en-US) object.

Document.elementFromPoint(Number x, Number y) (en-US)

Returns the element visible at the specified coordinates.

Document.enableStyleSheetsForSet(String name) (en-US)

Enables the style sheets for the specified style sheet set.

Document.exitPointerLock() (en-US) Экспериментальная возможность

Release the pointer lock.

Document.getElementsByClassName(String className)

Returns a list of elements with the given class name.

Document.getElementsByTagName(String tagName)

Returns a list of elements with the given tag name.

Document.getElementsByTagNameNS(String namespace, String tagName) (en-US)

Returns a list of elements with the given tag name and namespace.

Document.importNode(Node node, Boolean deep)

Returns a clone of a node from an external document.

document.mozSetImageElement (en-US) Non-standard

Allows you to change the element being used as the background image for a specified element ID.

Document.normalizeDocument()

Replaces entities, normalizes text nodes, etc.

Document.releaseCapture() (en-US) Non-standard

Releases the current mouse capture if it's on an element in this document.

Document.releaseEvents Non-standard Устарело

See window.releaseEvents (en-US).

document.routeEvent Non-standard

See window.routeEvent.

The Document interface is extended with the ParentNode interface:

Document.getElementById(String id)

Returns an object reference to the identified element.

Document.querySelector(String selector)

Returns the first Element node within the document, in document order, that matches the specified selectors.

Document.querySelectorAll(String selector)

Returns a list of all the Element nodes within the document that match the specified selectors.

The Document interface is extended with the XPathEvaluator (en-US) interface:

Document.createExpression(String expression, XPathNSResolver resolver) (en-US)

Compiles an XPathExpression (en-US) which can then be used for (repeated) evaluations.

Document.createNSResolver(Node resolver) (en-US)

Creates an XPathNSResolver (en-US) object.

Document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)

Evaluates an XPath expression.

Extension for HTML documents

The Document interface for HTML documents inherit from the HTMLDocument interface or, since HTML5, is extended for such documents:

Document.clear() (en-US) Non-standard Устарело

In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.

Document.close()

Closes a document stream for writing.

Document.execCommand(String command[, Boolean showUI[, String value]])

On an editable document, executes a formating command.

Document.getElementsByName(String name)

Returns a list of elements with the given name.

Document.getSelection()

Returns a Selection (en-US) object related to text selected in the document.

Document.hasFocus()

Returns true if the focus is currently located anywhere inside the specified document.

Document.open() (en-US)

Opens a document stream for writing.

Document.queryCommandEnabled(String command) (en-US)

Returns true if the formating command can be executed on the current range.

Document.queryCommandIndeterm(String command)

Returns true if the formating command is in an indeterminate state on the current range.

Document.queryCommandState(String command) (en-US)

Returns true if the formating command has been executed on the current range.

Document.queryCommandSupported(String command) (en-US)

Returns true if the formating command is supported on the current range.

Document.queryCommandValue(String command)

Returns the current value of the current range for a formatting command.

Document.registerElement(String tagname[, Object options])

Registers a new custom element in the browser and returns a constructor for the new element.

Document.write(String text)

Writes text in a document.

Document.writeln(String text)

Writes a line of text in a document.

Спецификации

Specification
DOM Standard
# interface-document
HTML Standard
# the-document-object
CSSOM View Module
# extensions-to-the-document-interface
Pointer Lock 2.0
# extensions-to-the-document-interface
Selection API
# extensions-to-document-interface

Совместимость с браузерами

BCD tables only load in the browser