Использование модели объекта документа
Модель объекта документа (DOM) — это API для работы с деревьями DOM HTML- и XML-документов (а также других документов в формате дерева). Это API лежит в основе описания страницы и служит основой для веб-скриптинга.
Что такое дерево DOM?
Дерево DOM — это древовидная структура, узлы которой представляют содержимое HTML- или XML-документа. Каждый HTML- или XML-документ имеет представление в виде дерева DOM. Например, рассмотрим следующий документ:
<html lang="en">
<head>
<title>My Document</title>
</head>
<body>
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>
Его дерево DOM выглядит так:
Хотя это дерево похоже на дерево DOM этого документа, оно не идентично, так как фактическое дерево DOM сохраняет пробелы.
Когда веб-браузер анализирует HTML-документ, он строит дерево DOM и затем использует его для отображения документа.
Что делает API документа?
API документа, также иногда называемое API DOM, позволяет изменять дерево DOM любым желаемым образом. Оно позволяет создавать HTML- или XML-документы с нуля или изменять содержимое заданного HTML- или XML-документа. Авторы веб-страниц могут редактировать DOM документа с помощью JavaScript, обращаясь к свойству document глобального объекта. Этот document объект реализует интерфейс Document.
Чтение и изменение дерева
Предположим, что автор хочет изменить заголовок вышеупомянутого документа и вместо одного абзаца вставить два. Следующий скрипт выполнит эту задачу:
HTML
<html lang="en">
<head>
<title>My Document</title>
</head>
<body>
<input type="button" value="Change this document." onclick="change()" />
<h2>Header</h2>
<p>Paragraph</p>
</body>
</html>
JavaScript
function change() {
// document.getElementsByTagName("h2") returns a NodeList of the <h2>
// elements in the document, and the first is number 0:
const header = document.getElementsByTagName("h2").item(0);
// The firstChild of the header is a Text node:
header.firstChild.data = "A dynamic document";
// Now header is "A dynamic document".
// Access the first paragraph
const para = document.getElementsByTagName("p").item(0);
para.firstChild.data = "This is the first paragraph.";
// Create a new Text node for the second paragraph
const newText = document.createTextNode("This is the second paragraph.");
// Create a new Element to be the second paragraph
const newElement = document.createElement("p");
// Put the text in the paragraph
newElement.appendChild(newText);
// Put the paragraph on the end of the document by appending it to
// the body (which is the parent of para)
para.parentNode.appendChild(newElement);
}
Создание дерева
Вы также можете создать это дерево полностью в JavaScript.
const root = document.createElement("html");
root.lang = "en";
const head = document.createElement("head");
const title = document.createElement("title");
title.appendChild(document.createTextNode("My Document"));
head.appendChild(title);
const body = document.createElement("body");
const header = document.createElement("h1");
header.appendChild(document.createTextNode("Header"));
const paragraph = document.createElement("p");
paragraph.appendChild(document.createTextNode("Paragraph"));
body.appendChild(header);
body.appendChild(paragraph);
root.appendChild(head);
root.appendChild(body);
Как узнать больше?
Теперь, когда вы знакомы с основными понятиями DOM, вы можете узнать больше о ключевых функциях API документа, прочитав как перемещаться по HTML-таблице с помощью JavaScript и интерфейсов DOM.
См. также
- Модель объекта документа DOM.
© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Using_the_Document_Object_Model