Enjoy 20% off all plans by following us on social media. Check out other promotions!
测验题

What is the DOM and how is it structured?

Topics
JAVASCRIPTHTML
在GitHub上编辑

TL;DR

The DOM, or Document Object Model, is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM is structured as a tree of objects, where each node represents part of the document, such as elements, attributes, and text.


What is the DOM and how is it structured?

Definition

The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an HTML, XHTML, or XML document as a tree structure. Each node in this tree represents a part of the document.

Structure

The DOM is structured as a hierarchical tree of nodes. Here are the main types of nodes:

  1. Document node: The root of the document tree. It represents the entire document.
  2. Element nodes: These represent HTML elements and form the bulk of the document tree.
  3. Attribute nodes: These are associated with element nodes and represent the attributes of those elements.
  4. Text nodes: These represent the text content within elements.
  5. Comment nodes: These represent comments in the HTML.

Example

Consider the following HTML:

<!doctype html>
<html>
<head>
<title>Document</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>

The DOM tree for this document would look like this:

Document
└── html
├── head
│ └── title
│ └── "Document"
└── body
├── h1
│ └── "Hello, World!"
└── p
└── "This is a paragraph."

Accessing and manipulating the DOM

JavaScript can be used to access and manipulate the DOM. Here are some common methods:

  • document.getElementById(id): Selects an element by its ID.
  • document.querySelector(selector): Selects the first element that matches a CSS selector.
  • element.appendChild(node): Adds a new child node to an element.
  • element.removeChild(node): Removes a child node from an element.

Example:

// Select the <h1> element
const heading = document.querySelector('h1');
// Change its text content
heading.textContent = 'Hello, DOM!';

Further reading

在GitHub上编辑