Что такое document в JavaScript?
Объект document позволяет работать со всей HTML структорой сайта за счёт языка JavaScript. Document является корневым объектом в DOM-структуре сайта.
Через объект вы можете работать со всеми HTML объектами на странице сайта. Вы можете находить элементы по их ID, классу или имени тега и добавлять к ним свойства и менять их значения. Также вы можете работать с HTML разметкой, добавляя или удаляя элементы из неё.
document.body.style.background = 'red'; // Установили что задний фон для тега body стал красным цветом
Что такое document в javascript
Для работы со структурой DOM в JavaScript предназначен объект document , который определен в глобальном объекте window . Для получения базовой информации о веб-странице объект document предоставляет ряд свойств:
- title : представляет заголовк документа (который указан в элементе )
- lastModified : содержит дату последнего изменения документа
- URL : содержит адрес URL текущего документа
- domain : содержит домент, к которому принадлежит веб-страница документа
- documentElement : предоставляет доступ к корневому элементу
- body : предоставляет доступ к элементу на веб-странице
- head : предоставляет доступ к элементу на веб-странице
- cookie : содержит коллекцию всех куки для текущего документа
- images : содержит коллекцию всех объектов изображений (элементов img)
- links : содержит коллекцию ссылок — элементов и , у которых определен атрибут href
- anchors : предоставляет доступ к коллекции элементов , у которых определен атрибут name
- forms : содержит коллекцию всех форм на веб-странице
Эти свойства не предоставляют доступ ко всем элементам, однако позволяют получить наиболее часто используемые элементы на веб-странице. Например, получим корневой узел документа:
METANIT.COM
В результате на консоль будет выведено содержимое текущей веб-страницы, как оно определено в коде выше.
Или выведем базовую информацию о документе:
METANIT.COM
Консольный вывод в моем случае:
METANIT.COM 10/27/2023 20:45:11 file:///Users/eugene/Documents/app/index.html
Получим все изображения на странице:
METANIT.COM ![]()
![]()
Подобно тому, как в коде html мы можем установить атрибуты у элемента img, так и в коде javascript мы можем через свойства src и alt получить и установить значения этих атрибутов. Причем в данном случае не важно, существуют или нет файлы изображений. Консольный вывод будет наподобие следующего:
Url: "app/picture_4.jpg" Alt:"Новая картинка" Url: "app/picure2.png" Alt:"Картинка 2" Url: "app/picure3.png" Alt:"Картинка 3"
Рассмотрим получение всех ссылок на странице:
METANIT.COM Статья 1 Статья 2 Статья 3
Опять же, так как у ссылки определен атрибут href , то при переборе ссылок мы можем получить его значение.
Document
Объект 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.load чтобы обозначить асинхронный запрос.
Возвращает кодировку документа.
Указывает в каком режиме (Quirks или Strict) рендерился документ.
Возвращает Content-Type из MIME заголовка текущего документа.
Возвращает Document Type Definition (DTD) текущего документа .
Возвращает Element, который является первым дочерним элементом документа. Для HTML документов это HTML-элемент.
Возвращает URL документа.
Должен вернуть DOMConfiguration объект.
Возвращает DOM implementation связанную с текущим документом.
Возвращает кодировку, которая использовалась во время парсинга документа.
Возвращает имя последнего включённого набора таблиц стилей. Имеет значение null , пока таблица стилей не будет изменена путём установки значения selectedStyleSheetSet (en-US).
true если этот документ является синтетическим, например, отдельные изображения, видео, аудио файлы, или тому подобные.
true когда документ находится в full-screen mode .
Элемент, который в данный момент находится в полноэкранном режиме для этого документа.
true if calling element.mozRequestFullscreen() (en-US) would succeed in the curent document.
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.
Returns the preferred style sheet set as specified by the page author.
Returns which style sheet set is currently in use.
Returns a list of the style sheet objects on the current document.
Returns a list of the style sheet sets available on the document.
Returns the encoding as determined by the XML declaration.
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 .
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:
Returns the currently focused element.
Returns or sets the color of active links in the document body.
Returns a list of all of the anchors in the document.
Returns an ordered list of the applets within a document.
Gets/sets the background color of the current document.
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
Returns a reference to the window object.
Gets/sets the ability to edit the whole document.
Gets/sets directionality (rtl/ltr) of the document.
Returns the domain of the current document.
Gets/sets the foreground color, or text color, of the current document.
Gets/sets the height of the current document.
Returns a list of the images in the current document.
Returns the date on which the document was last modified.
Gets/sets the color of hyperlinks in the document.
Returns a list of all the hyperlinks in the document.
Returns the URI of the current document.
Returns a list of the available plugins.
Returns loading status of the document.
Returns the URI of the page that linked to this page.
Returns the title of the current document.
Returns a string containing the URL of the current document.
Gets/sets the color of visited hyperlinks.
Returns the width of the current document.
Event handlers
Document.onpointerlockchange Экспериментальная возможность
Returns the event handling code for the pointerlockchange (en-US) event.
Returns the event handling code for the pointerlockerror (en-US) event.
Returns the event handling code for the readystatechange event.
Methods
Примечание: The Document interface also inherits from the Node and EventTarget interfaces.
Adopt node from an external document.
Creates a new Attr object and returns it.
Creates a new attribute node in a given namespace and returns it.
Creates a new CDATA node and returns it.
Creates a new comment node and returns it.
Creates a new document fragment.
Creates a new element with the given tag name.
Creates a new element with the given tag name and namespace URI.
Creates a new entity reference object and returns it.
Creates an event object.
Creates a Range object.
Creates a text node.
Returns the element visible at the specified coordinates.
Enables the style sheets for the specified style sheet set.
Release the pointer lock.
Returns a list of elements with the given class name.
Returns a list of elements with the given tag name.
Returns a list of elements with the given tag name and namespace.
Returns a clone of a node from an external document.
Allows you to change the element being used as the background image for a specified element ID.
Replaces entities, normalizes text nodes, etc.
Releases the current mouse capture if it’s on an element in this document.
The Document interface is extended with the ParentNode interface:
Returns an object reference to the identified element.
Returns the first Element node within the document, in document order, that matches the specified selectors.
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:
Compiles an XPathExpression (en-US) which can then be used for (repeated) evaluations.
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:
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
Closes a document stream for writing.
On an editable document, executes a formating command.
Returns a list of elements with the given name.
Returns a Selection (en-US) object related to text selected in the document.
Returns true if the focus is currently located anywhere inside the specified document.
Opens a document stream for writing.
Returns true if the formating command can be executed on the current range.
Returns true if the formating command is in an indeterminate state on the current range.
Returns true if the formating command has been executed on the current range.
Returns true if the formating command is supported on the current range.
Returns the current value of the current range for a formatting command.
Registers a new custom element in the browser and returns a constructor for the new element.
Writes text in a document.
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
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 3 авг. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Объект document в JavaScript. Методы и свойства объекта document
От автора: приветствую вас, друзья. В этой статье мы с вами познакомимся с объектом document в JavaScript, а также узнаем, как выбирать элементы верстки в документе и манипулировать выбранными элементами.
Начнем с того, что такое объект document. Объект document, как следует из названия, — это ни что иное, как HTML страница, с которой мы работаем в данный момент или, как еще говорят, документ. В данной статье мы не будем останавливаться на понятии объектной модели документа, об этом вы можете узнать из наших уроков и курса по JavaScript.
Мы же сразу перейдем к методам объекта document. Итак, у нас есть простейшая верстка:
