Document
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since июль 2015 г..
* Some parts of this feature may have varying levels of support.
Каждая веб-страница, которая загружается в браузер, имеет свой собственный объект document. Интерфейс документа служит точкой входа для получения содержимого веб-страницы (всего DOM - дерева, включая такие элементы как <body> и <table>), а также обеспечивает функциональность, которая является глобальной для документа, например, для получения URL-адреса страницы или создания новых элементов в документе).
Объект document может быть получен из разных API:
- Чаще всего используется прямой доступ к объекту document из сценариев scripts которые подгружаются документом. (Этот же объект доступен как
window.document.) - Через свойство
contentDocumentобъекта iframe. - Как ответ
responseXMLобъектаXMLHttpRequest. - Доступ к документу может быть получен из элемента или узла через свойство
ownerDocument.
В зависимости от вида документа (т.е. HTML или XML) у объекта document могут быть доступны разные API.
- Все объекты документов реализуют интерфейс
Document(и следовательноNodeиEventTargetинтерфейсы). Таким образом основные свойства и методы, описанные на этой странице, доступны для всех видов документов. - В современных браузерах некоторые документы (т.е. те, которые содержат контент
text/html) также реализуютHTMLDocumentинтерфейс. - В современных браузерах SVG документы реализуют
SVGDocumentинтерфейс.
В будущем все эти интерфейсы будут сведены в один интерфейс - Document.
Свойства
Примечание:
Интерфейс Document наследует также интерфейсы Node и EventTarget.
Document.allУстарело Не стандартно-
Обеспечивает доступ ко всем элементам с идентификаторами (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-
Возвращает DOM implementation связанную с текущим документом.
Document.inputEncodingУстарело-
Возвращает кодировку, которая использовалась во время парсинга документа.
Document.lastStyleSheetSet-
Возвращает имя последнего включённого набора таблиц стилей. Имеет значение
null, пока таблица стилей не будет изменена путём установки значенияselectedStyleSheetSet. Document.mozSyntheticDocumentНе стандартно-
trueесли этот документ является синтетическим, например, отдельные изображения, видео, аудио файлы, или тому подобные. Document.mozFullScreenНе стандартно-
trueкогда документ находится вfull-screen mode. Document.mozFullScreenElementНе стандартно-
Элемент, который в данный момент находится в полноэкранном режиме для этого документа.
Document.mozFullScreenEnabledНе стандартно-
trueif callingelement.mozRequestFullscreen()would succeed in the curent document. Document.pointerLockElementЭкспериментальная возможность-
Returns the element set as the target for mouse events while the pointer is locked.
nullif lock is pending, pointer is unlocked, or if the target is in another document. Document.preferredStyleSheetSet-
Returns the preferred style sheet set as specified by the page author.
Document.selectedStyleSheetSet-
Returns which style sheet set is currently in use.
Document.styleSheets-
Returns a list of the style sheet objects on the current document.
Document.styleSheetSets-
Returns a list of the style sheet sets available on the document.
Document.xmlEncodingУстарело-
Returns the encoding as determined by the XML declaration.
Document.xmlStandaloneУстарело-
Returns
trueif the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), elsefalse. Document.xmlVersionУстарело-
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. -
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Устарело-
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Не стандартно-
Gets/sets the height of the current document.
Document.images-
Returns a list of the images in the current document.
Document.lastModified-
Returns the date on which the document was last modified.
Document.linkColorУстарело-
Gets/sets the color of hyperlinks in the document.
Document.links-
Returns a list of all the hyperlinks in the document.
Document.location-
Returns the URI of the current document.
Document.plugins-
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-
Returns the title of the current document.
Document.URL-
Returns a string containing the URL of the current document.
Document.vlinkColorУстарело-
Gets/sets the color of visited hyperlinks.
Document.widthНе стандартно-
Returns the width of the current document.
Event handlers
Document.onpointerlockchangeЭкспериментальная возможность-
Returns the event handling code for the
pointerlockchangeevent. Document.onpointerlockerrorЭкспериментальная возможность-
Returns the event handling code for the
pointerlockerrorevent. Document.onreadystatechange-
Returns the event handling code for the
readystatechangeevent.
Methods
Примечание:
The Document interface also inherits from the Node and EventTarget interfaces.
Document.adoptNode(Node node)-
Adopt node from an external document.
Document.captureEvents(String eventName)Устарело-
See
window.captureEvents. Document.caretPositionFromPoint(Number x, Number y)-
Gets a
CaretPositionbased on two coordinates. Document.createAttribute(String name)-
Creates a new
Attrobject and returns it. Document.createAttributeNS(String namespace, String name)-
Creates a new attribute node in a given namespace and returns it.
Document.createCDATASection(String data)-
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)-
Creates a new element with the given tag name and namespace URI.
Document.createEntityReference(String name)-
Creates a new entity reference object and returns it.
Document.createEvent(String interface)-
Creates an event object.
Document.createNodeIterator(Node root[, Number whatToShow[, NodeFilter filter]])-
Creates a
NodeIteratorobject. Document.createProcessingInstruction(String target, String data)-
Creates a new
ProcessingInstructionobject. Document.createRange()-
Creates a
Rangeobject. Document.createTextNode(String text)-
Creates a text node.
Document.createTreeWalker(Node root[, Number whatToShow[, NodeFilter filter]])-
Creates a
TreeWalkerobject. Document.elementFromPoint(Number x, Number y)-
Returns the element visible at the specified coordinates.
Document.enableStyleSheetsForSet(String name)-
Enables the style sheets for the specified style sheet set.
Document.exitPointerLock()Экспериментальная возможность-
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)-
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Не стандартно-
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()Не стандартно-
Releases the current mouse capture if it's on an element in this document.
Document.releaseEventsНе стандартно Устарело-
See
window.releaseEvents. document.routeEventНе стандартно-
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 interface:
Document.createExpression(String expression, XPathNSResolver resolver)-
Compiles an
XPathExpressionwhich can then be used for (repeated) evaluations. Document.createNSResolver(Node resolver)-
Creates an
XPathNSResolverobject. 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()Не стандартно Устарело-
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
Selectionobject related to text selected in the document. Document.hasFocus()-
Returns
trueif the focus is currently located anywhere inside the specified document. Document.open()-
Opens a document stream for writing.
Document.queryCommandEnabled(String command)-
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)-
Returns true if the formating command has been executed on the current range.
Document.queryCommandSupported(String command)-
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.
Спецификации
Совместимость с браузерами
Loading…