Объект document как точка входа в DOM
window.document в JavaScript
Основной путь: объект document доступен как свойство window.document и служит точкой входа в DOM текущей страницы. Через него выполняются выборка узлов, создание элементов, подписка на события, чтение метаданных документа и управление структурой.
const root = document.getElementById('app');
root.textContent = 'Данные загружены';
const button = document.createElement('button');
button.textContent = 'Показать';
button.addEventListener('click', () => {
document.body.classList.add('panel-open');
});
document.body.appendChild(button);
Window document js (window.document в javascript)
Код находит контейнер, меняет текст, создаёт кнопку, добавляет обработчик и вставляет кнопку в body. Ссылка window.document и document указывают на один объект.
console.log(document === window.document);
console.log(document.readyState);
Js window document (свойство window.document)
true complete
Как выбрать один элемент без сложных библиотек?
Метод querySelector принимает CSS-селектор и возвращает первый подходящий элемент или null.
const title = document.querySelector('.title');
const link = document.querySelector('a[data-role=main]');
console.log(title?.textContent);
console.log(link?.href);
Заголовок https://example.com/
Как получить все элементы по селектору?
querySelectorAll возвращает статическую коллекцию NodeList. Для перебора подходят forEach и for...of.
const items = document.querySelectorAll('.item');
items.forEach((item, index) => {
item.dataset.index = String(index);
});
console.log(items.length);
3
Как создать и вставить новый узел?
Создание узла выполняется через document.createElement. Вставка доступна через append, prepend, before, after, replaceWith.
const card = document.createElement('article');
card.className = 'card';
card.innerHTML = '<h3>Новость</h3><p>Текст</p>';
const list = document.querySelector('.list');
list.append(card);
Для пользовательских данных innerHTML опасен. Безопаснее создавать текстовые узлы.
const p = document.createElement('p');
p.textContent = 'Безопасный текст';
document.body.append(p);
Как обрабатывать события через document?
Подписка на document позволяет применять делегирование. Событие всплывает от целевого элемента к документу.
document.addEventListener('click', (event) => {
const target = event.target.closest('[data-action]');
if (!target) return;
console.log(target.dataset.action);
});
save
Как читать формы и поля ввода?
Свойство document.forms даёт доступ к формам. Элементы формы доступны по имени или через querySelector.
const form = document.forms.login;
const email = form.elements.email.value;
const remember = form.elements.remember.checked;
console.log({ email, remember });
{ email: 'user@example.com', remember: true }
Как менять атрибуты, классы и стили?
Для атрибутов применяется setAttribute и getAttribute, для классов classList, для инлайновых стилей style.
const box = document.querySelector('.box');
box.setAttribute('data-state', 'active');
box.classList.add('visible');
box.style.setProperty('--size', '120px');
console.log(box.getAttribute('data-state'));
active
Как получить сведения о документе?
Объект document хранит заголовок, URL, состояние загрузки, корневые элементы и cookie.
console.log(document.title);
console.log(document.URL);
console.log(document.documentElement.tagName);
console.log(document.body?.tagName);
Моя страница https://example.com/page HTML BODY
Типичная ошибка: обращение к элементу до его появления в DOM. Скрипт в <head> без defer может получить null.
const el = document.querySelector('.late');
console.log(el);
null
Решение: размещение скрипта перед </body>, атрибут defer или ожидание DOMContentLoaded.
document.addEventListener('DOMContentLoaded', () => {
const el = document.querySelector('.late');
console.log(el?.textContent);
});
Проблема XSS: innerHTML с данными пользователя может выполнить опасный код. Для текста применяется textContent, для разметки нужна очистка.
Проблема живых коллекций: getElementsByClassName и getElementsByTagName возвращают живые коллекции, а querySelectorAll статическую. Изменения DOM меняют живую коллекцию во время цикла.
const live = document.getElementsByClassName('item');
console.log(live.length);
document.body.append(document.createElement('div'));
console.log(live.length);
2 2
Проблема document.write: после загрузки страницы вызов document.write перезаписывает документ. Для динамических данных применяются DOM-методы.
Проблема iframe: доступ к iframe.contentDocument возможен только для same-origin. Для чужого домена браузер выбрасывает ошибку безопасности.
Расширенные примеры работы с document
Наблюдение за изменениями DOM
const target = document.getElementById('feed');
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
console.log(mutation.type, mutation.addedNodes.length);
});
});
observer.observe(target, { childList: true, subtree: true });
const item = document.createElement('div');
item.textContent = 'Новая запись';
target.append(item);
childList 1
Единый обработчик для списка
document.addEventListener('click', (event) => {
const btn = event.target.closest('button[data-id]');
if (!btn) return;
console.log('id:', btn.dataset.id);
});
id: 42
Массовая вставка без лишних перерисовок
const fragment = document.createDocumentFragment();
for (let i = 1; i <= 3; i++) {
const li = document.createElement('li');
li.textContent = 'Пункт ' + i;
fragment.append(li);
}
document.querySelector('ul').append(fragment);
<ul> <li>Пункт 1</li> <li>Пункт 2</li> <li>Пункт 3</li> </ul>
Клонирование template
const tpl = document.getElementById('card-template');
const copy = tpl.content.cloneNode(true);
copy.querySelector('.name').textContent = 'Анна';
document.body.append(copy);
В DOM появляется карточка с именем Анна
Пользовательское событие через document
document.addEventListener('app:ready', (event) => {
console.log(event.detail.version);
});
const event = new CustomEvent('app:ready', { detail: { version: '1.0' } });
document.dispatchEvent(event);
1.0
Управление активным элементом
const input = document.querySelector('input');
input.focus();
console.log(document.activeElement === input);
input.blur();
console.log(document.activeElement === document.body);
true true
Измерение позиции элемента
const rect = document.querySelector('.box').getBoundingClientRect();
console.log(rect.top, rect.left, rect.width, rect.height);
120 40 300 200
Доступ к документу iframe
const frame = document.querySelector('iframe');
frame.addEventListener('load', () => {
const innerDoc = frame.contentDocument;
console.log(innerDoc.title);
});
Внутренняя страница
Динамическая загрузка скрипта
const script = document.createElement('script');
script.src = 'https://example.com/widget.js';
script.async = true;
script.onload = () => console.log('loaded');
document.head.append(script);
loaded
Обход текстовых узлов через TreeWalker
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT
);
let node;
while ((node = walker.nextNode())) {
if (node.textContent.trim()) console.log(node.textContent.trim());
}
Заголовок Абзац
Сбор данных формы
const form = document.querySelector('form');
const data = new FormData(form);
for (const [key, value] of data.entries()) {
console.log(key, value);
}
email user@example.com remember on
Отслеживание видимости элемента
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
console.log(entry.target.id, entry.isIntersecting);
});
});
observer.observe(document.getElementById('banner'));
banner true
Выборка через document.evaluate
const result = document.evaluate(
'//a',
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
console.log(result.snapshotLength);
3
Подключение CSSStyleSheet через adoptedStyleSheets
const sheet = new CSSStyleSheet();
sheet.replaceSync('.accent { color: crimson; }');
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
Элементы с классом accent получают цвет crimson
Переход вида при изменении DOM
document.startViewTransition(() => {
document.body.classList.toggle('dark');
});
Смена темы сопровождается анимацией, если браузер поддерживает API
Создание customized built-in элемента
class FancyButton extends HTMLButtonElement {
connectedCallback() {
this.classList.add('fancy');
}
}
customElements.define('fancy-button', FancyButton, { extends: 'button' });
const btn = document.createElement('button', { is: 'fancy-button' });
document.body.append(btn);
Кнопка получает класс fancy после вставки в документ
Выделение фрагмента через Range
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());
Текст абзаца
Создание комментария
const comment = document.createComment('служебная метка');
document.body.prepend(comment);
console.log(comment.nodeType);
8
Импорт узла из другого документа
const iframe = document.querySelector('iframe');
const foreign = iframe.contentDocument.querySelector('.widget');
const imported = document.importNode(foreign, true);
document.body.append(imported);
Узел из iframe появляется в основном документе
Создание и установка атрибута
const attr = document.createAttribute('data-status');
attr.value = 'ready';
document.body.setAttributeNode(attr);
console.log(document.body.getAttribute('data-status'));
ready