window.document как точка входа в объектную модель документа

Раздел: Веб-разработка -> window

Свойство window.document в JavaScript

window.document это ссылка на объект Document, который связан с текущим окном браузера. В браузерной среде window.document === document возвращает true. Свойство даёт доступ к DOM, метаданным, cookie, формам, изображениям, таблицам стилей и другим коллекциям.

Основной подход: в браузерном коде можно использовать document напрямую. Явное обращение window.document имеет смысл, когда требуется подчеркнуть работу с глобальным окном, например при проверке окружения или при доступе к документу фрейма через iframe.contentWindow.document.

console.log(window.document === document);
console.log(window.document.title);
window.document.title = 'Новый заголовок';
console.log(document.title);

Window document js (window.document в javascript)

true
Текущий заголовок
Новый заголовок

Js window document (свойство window.document)

Пояснение: window.document и document указывают на один объект. Изменение свойства title через один идентификатор отражается на другом.

Доступные свойства и методы:

  • document.documentElement корневой элемент html.
  • document.body элемент body.
  • document.head элемент head.
  • document.URL, document.readyState, document.referrer.
  • document.getElementById, document.querySelector, document.querySelectorAll.
  • document.createElement, document.createTextNode, document.createDocumentFragment.
  • document.cookie, document.forms, document.images, document.links, document.scripts, document.styleSheets.

Проблема: в Web Workers и Node.js глобальный объект window отсутствует. Код window.document в таком окружении приводит к ошибке. Решение: проверка typeof window !== 'undefined' и typeof document !== 'undefined'.

if (typeof window !== 'undefined' && window.document) {
  console.log(window.document.readyState);
} else {
  console.log('DOM недоступен');
}

Как получить документ внутри iframe?

Для same-origin iframe используется iframe.contentWindow.document или iframe.contentDocument. Для cross-origin доступ запрещён политикой безопасности.

const frame = document.querySelector('#frame');
const innerDoc = frame.contentDocument || frame.contentWindow.document;
console.log(innerDoc.title);
Заголовок внутреннего документа

При cross-origin возникает SecurityError. Решение: postMessage для обмена данными.

Как обрабатывать отсутствие window.document при серверном рендеринге?

В Node.js нет DOM. Проверка typeof document !== 'undefined' помогает отделить серверный и клиентский код.

function getTitle() {
  if (typeof document === 'undefined') {
    return 'Серверный рендеринг';
  }
  return document.title;
}
console.log(getTitle());
Серверный рендеринг

Импорт модуля, который сразу обращается к document, может сломать SSR. Решение: обращение к DOM внутри useEffect, onMounted или после проверки окружения.

Как определить, когда документ готов к работе?

Свойство document.readyState возвращает loading, interactive или complete. Событие DOMContentLoaded срабатывает после разбора HTML.

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', onReady);
} else {
  onReady();
}
function onReady() {
  console.log('DOM готов');
}
DOM готов

Как менять заголовок и мета-теги через document?

document.title = 'Новая страница';
const meta = document.createElement('meta');
meta.name = 'description';
meta.content = 'Описание страницы';
document.head.appendChild(meta);
console.log(document.title);
Новая страница

Как разобрать HTML-строку через document.implementation?

const parser = new DOMParser();
const doc = parser.parseFromString('
Привет
', 'text/html'); console.log(doc.body.textContent);
Привет

Альтернатива: document.implementation.createHTMLDocument.

const htmlDoc = document.implementation.createHTMLDocument('Временный');
htmlDoc.body.innerHTML = '

Текст

'; console.log(htmlDoc.body.firstChild.textContent);
Текст

Как читать и записывать cookie через document.cookie?

document.cookie = 'user=Anna; path=/; max-age=3600';
console.log(document.cookie);
user=Anna

Cookie не удаляются через простое присваивание. Для удаления устанавливается max-age=0 или прошедшая дата. HttpOnly cookie недоступны через JavaScript.

Как найти текущий выполняемый script через document?

https://example.com/app.js

Как получить элементы внутри Shadow DOM?

document.querySelector не проникает в shadow root. Доступ выполняется через shadowRoot.querySelector.

const host = document.querySelector('#host');
const root = host.attachShadow({ mode: 'open' });
root.innerHTML = 'Внутри';
console.log(root.querySelector('span').textContent);
console.log(document.querySelector('#host span'));
Внутри
null

Как типизировать window.document в TypeScript?

const doc: Document = window.document;
const el = doc.getElementById('app');
console.log(el?.tagName);
DIV

В конфигурации lib должны быть указаны DOM и ES2015 или выше.

Какие проблемы возникают при document.write?

document.write('

Заголовок

');

document.write после загрузки страницы заменяет весь документ. В актуальном коде применяются appendChild, insertAdjacentHTML или innerHTML. Для динамических скриптов используется document.createElement('script').

Расширенные примеры с window.document

Как перебрать все формы и поля документа?

Коллекция document.forms содержит формы, а elements поля.

Пример
const forms = window.document.forms;
for (const form of forms) {
  console.log('Форма:', form.name || form.id);
  for (const field of form.elements) {
    console.log(field.name, field.type);
  }
}
Форма: login
user text
pass password

Как наблюдать за изменениями DOM?

Пример
const target = document.querySelector('#app');
const observer = new MutationObserver((mutations) => {
  for (const m of mutations) {
    console.log(m.type, m.addedNodes.length);
  }
});
observer.observe(target, { childList: true, subtree: true });
target.appendChild(document.createElement('span'));
childList 1

Как работать с Range и Selection через document?

Пример
const range = document.createRange();
const p = document.querySelector('p');
range.selectNodeContents(p);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
console.log(selection.toString());
Текст абзаца

Как выполнить XPath-запрос в документе?

Пример
const result = document.evaluate('//a[@href]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < result.snapshotLength; i++) {
  console.log(result.snapshotItem(i).href);
}
https://example.com/

Как использовать DocumentFragment для массовой вставки?

Пример
const fragment = document.createDocumentFragment();
for (let i = 0; i < 3; i++) {
  const li = document.createElement('li');
  li.textContent = 'Пункт ' + i;
  fragment.appendChild(li);
}
document.querySelector('ul').appendChild(fragment);
console.log(document.querySelectorAll('li').length);
3

Как переносить узлы между документами?

Пример
const frame = document.querySelector('#frame');
const innerDoc = frame.contentDocument;
const node = innerDoc.querySelector('.item');
const imported = document.importNode(node, true);
document.body.appendChild(imported);
console.log(imported.ownerDocument === document);
true

document.adoptNode меняет владельца узла без клонирования.

Как читать CSS-правила через document.styleSheets?

Пример
const sheet = document.styleSheets[0];
const rules = sheet.cssRules || sheet.rules;
for (const rule of rules) {
  console.log(rule.selectorText, rule.style?.color);
}
.title rgb(0, 0, 0)

Для cross-origin таблиц стилей чтение cssRules вызывает SecurityError. Обход: fetch с CORS.

Как связать Custom Elements с document?

Пример
class MyTag extends HTMLElement {
  connectedCallback() {
    this.textContent = 'Свой тег';
  }
}
customElements.define('my-tag', MyTag);
document.body.appendChild(document.createElement('my-tag'));
console.log(document.querySelector('my-tag').textContent);
Свой тег

Как отслеживать видимость и фокус документа?

Пример
console.log(document.visibilityState);
console.log(document.hasFocus());
document.addEventListener('visibilitychange', () => {
  console.log('Новое состояние:', document.visibilityState);
});
visible
true
Новое состояние: hidden

Как включить режим редактирования документа?

Пример
document.designMode = 'on';
console.log(document.designMode);
document.designMode = 'off';
on

Как создать XML-документ?

Пример
const xmlDoc = document.implementation.createDocument('', 'root', null);
const item = xmlDoc.createElement('item');
item.textContent = 'Значение';
xmlDoc.documentElement.appendChild(item);
const xml = new XMLSerializer().serializeToString(xmlDoc);
console.log(xml);
Значение

Как получить активный элемент документа?

Пример
const input = document.querySelector('input');
input.focus();
console.log(document.activeElement === input);
true

Как разобрать cookie без библиотек?

Пример
function parseCookies() {
  return document.cookie.split('; ').reduce((acc, pair) => {
    const [key, value] = pair.split('=');
    acc[key] = decodeURIComponent(value);
    return acc;
  }, {});
}
document.cookie = 'theme=dark; path=/';
console.log(parseCookies().theme);
dark

Как использовать TreeWalker для обхода текстовых узлов?

Пример
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
let count = 0;
while (walker.nextNode()) {
  count++;
}
console.log('Текстовых узлов:', count);
Текстовых узлов: 12

Как обработать cross-origin iframe?

Пример
const frame = document.querySelector('iframe');
try {
  console.log(frame.contentDocument.body.innerHTML);
} catch (e) {
  console.log('Нет доступа:', e.name);
}
frame.contentWindow.postMessage({ type: 'ping' }, 'https://other.example');
Нет доступа: SecurityError

Как получить элемент по текущему script?

Пример
const scripts = document.scripts;
const current = document.currentScript;
console.log(scripts.length > 0, current?.async);
true false

Как использовать document.open и document.close?

Пример
const w = window.open('', '_blank');
w.document.open();
w.document.write('

Новое окно

'); w.document.close();
Новое окно

Всплывающие окна могут блокироваться. document.write после загрузки заменяет содержимое. Для безопасности применяется document.createElement.

Как получить элемент прокрутки документа?

Пример
console.log(document.scrollingElement === document.documentElement);
console.log(document.characterSet);
console.log(document.contentType);
true
UTF-8
text/html

Свойство window.document - comments

En
Js window document (javascript)