HTML DOM Documents
When an HTML document is loaded into a web browser, it becomes a document object.
The document object is the root node of the HTML document.
The document object is a property of the window object.
The document object is accessed with:
window.document or just document
Examples
Document Object Properties and Methods
The following properties and methods can be used on HTML documents:
Property / Method | Description |
---|---|
activeElement | Returns the currently focused element in the document |
addEventListener() | Attaches an event handler to the document |
adoptNode() | Adopts a node from another document |
anchors | Deprecated |
applets | Deprecated |
baseURI | Returns the absolute base URI of a document |
body | Sets or returns the document’s body (the element) |
charset | Deprecated |
characterSet | Returns the character encoding for the document |
close() | Closes the output stream previously opened with document.open() |
cookie | Returns all name/value pairs of cookies in the document |
createAttribute() | Creates an attribute node |
createComment() | Creates a Comment node with the specified text |
createDocumentFragment() | Creates an empty DocumentFragment node |
createElement() | Creates an Element node |
createEvent() | Creates a new event |
createTextNode() | Creates a Text node |
defaultView | Returns the window object associated with a document, or null if none is available. |
designMode | Controls whether the entire document should be editable or not. |
doctype | Returns the Document Type Declaration associated with the document |
documentElement | Returns the Document Element of the document (the element) |
documentMode | Deprecated |
documentURI | Sets or returns the location of the document |
domain | Returns the domain name of the server that loaded the document |
domConfig | Deprecated |
embeds | Returns a collection of all elements the document |
execCommand() | Deprecated |
forms | Returns a collection of all elements in the document |
getElementById() | Returns the element that has the ID attribute with the specified value |
getElementsByClassName() | Returns an HTMLCollection containing all elements with the specified class name |
getElementsByName() | Returns an live NodeList containing all elements with the specified name |
getElementsByTagName() | Returns an HTMLCollection containing all elements with the specified tag name |
hasFocus() | Returns a Boolean value indicating whether the document has focus |
head | Returns the element of the document |
images | Returns a collection of all elements in the document |
implementation | Returns the DOMImplementation object that handles this document |
importNode() | Imports a node from another document |
inputEncoding | Deprecated |
lastModified | Returns the date and time the document was last modified |
links | Returns a collection of all and elements in the document that have a href attribute |
normalize() | Removes empty Text nodes, and joins adjacent nodes |
normalizeDocument() | Deprecated |
open() | Opens an HTML output stream to collect output from document.write() |
querySelector() | Returns the first element that matches a specified CSS selector(s) in the document |
querySelectorAll() | Returns a static NodeList containing all elements that matches a specified CSS selector(s) in the document |
readyState | Returns the (loading) status of the document |
referrer | Returns the URL of the document that loaded the current document |
removeEventListener() | Removes an event handler from the document (that has been attached with the addEventListener() method) |
renameNode() | Deprecated |
scripts | Returns a collection of elements in the document |
strictErrorChecking | Deprecated |
title | Sets or returns the title of the document |
URL | Returns the full URL of the HTML document |
write() | Writes HTML expressions or JavaScript code to a document |
writeln() | Same as write(), but adds a newline character after each statement |
Объект Document в JavaScript — содержимое окна браузера
На этом уроке мы рассмотрим объект document , который отвечает за HTML документ, загруженный в окно или вкладку браузера. С помощью этого объекта в JavaScript Вы можете не только получить различную информацию об этом документе, но и изменить его.
Основные объекты браузера
Перед тем как перейти к изучению объекта document , давайте вспомним, какие нам в JavaScript доступны объекты и за что они отвечают.
При открытии документа браузер автоматически создаёт набор объектов для JavaScript, с помощью которых Вы можете не только работать с этим документом (объект document ), но и управлять самим браузером (объекты window , location , navigator , screen , history ). Все эти объекты образуют объектную модель браузера (BOM — Browser Object Model).
Главным объектом в этой модели является объект window . Все остальные объекты доступны как свойства объекта window ( window.document , window.location и т.д.). Если мы работаем с текущим окном, то » window. » можно опускать, т.е. document , location и т.д. Объект location — отвечает за адресную строку, объект history — за кнопки вперёд и назад, объект, объект screen — за экран пользователя, объект window — отвечает за само окно, а также позволяет изменять его размеры, перемещать его и т.д., navigator — позволяет получить информацию о браузере.
Наибольший интерес среди всех этих объектов для нас предоставляет именно объект document , т.к. он отвечает за документ, загруженный в окно или вкладку браузера. Он даёт начало объектной модели документа (DOM — Document Object Model), которая стандартизована в спецификации и поддерживается всеми браузерами.
К рассмотрению этой модели мы приступим на следующих уроках. На этом уроке мы рассмотрим некоторые свойства и методы объекта document, т.е. такие которые особого отношения к объектной модели документа не имеют.
Свойства и методы объекта document
Объект document содержит следующие «общие» свойства и методы:
- Свойство document.implementation — возвращает объект DOMImplementation, ассоциированный с текущим документом. Например, определим, поддерживается ли указанная возможность в браузере:
Свойство document.characterSet — возвращает кодировку, которая используется для рендеринга текущего документа. Данное значение может отличаться от кодировки указанной в HTML странице, т.к. пользователь может её переопределить, т.е. выбрать в соответствующем меню браузера другую кодировку, которая будет использоваться для отображения текущего документа.
Свойство document.inputEncoding — возвращает кодировку, которая использовалась во время синтаксического разбора (парсинга) документа. Если документ создан в памяти, то данное свойство возвращает значение null . Данное свойство доступно только для чтения.
Свойство document.lastModified — возвращает строку, содержащую дату и время последнего изменения текущего документа. Gecko и Internet Explorer возвращают время в часовом поясе локального компьютера, WebKit — в UTC.
alert(document.lastModified);
- uninitialized — процесс загрузки ещё не начался;
- loading — идёт процесс загрузки;
- loaded — загрузка HTML кода завершена;
- interactive — документ достаточно загружен для того, чтобы пользователь мог взаимодействовать с ним. Код JavaScript может начать выполняться только на этом этапе;
- complete — документ полностью загружен.
В большинстве случаев, код JavaScript обычно выполняется и вызывается после того, как документ полностью загружен, т.е. когда он находится в состоянии complete .
document.onreadystatechange = function () { if (document.readyState == "complete") { //выполнить код, после того как документ полностью загружен } }
- Выведем все cookie связанные с текущим документом, т.е. пары ключ=значение : document.cookie ;
- Запишем новый cookie: document.cookie = «test1 = Test1»;
- Запишем ещё один новый cookie: document.cookie = «test2 = Test2»;
- Выведем все cookie связанные с текущим документом: document.cookie .
Метод document.write() — предназначен для вывода в документ строки, указанной в качестве параметра данного метода. Если данный метод вызывается в процессе загрузки документа, то он выводит строку в текущем месте. В том случае, если данный метод вызывается после загрузки документа, то он приводит к полной очистке этого документа и вывода строчки. Это происходит, потому что после загрузки документа браузер уже полностью построил DOM и в документ уже нельзя внести изменения таким способом, а только с помощью добавления узлов в объектную модель документа. Например, вывести строку «I LOVE JAVASCRIPT»:
document.write("I LOVE JAVASCRIPT");
Открыть и сформировать новый документ