What is the DOM and how is it structured?
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.
A document as a node tree
The DOM represents a parsed document as connected node objects; elements, text, and comments are node types within that tree.
DOM APIs navigate and mutate these node relationships; the tree is an in-memory object model, not the original HTML source 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:
- Document node: The root of the document tree. It represents the entire document.
- Element nodes: These represent HTML elements and form the bulk of the document tree.
- Attribute nodes: These are associated with element nodes and represent the attributes of those elements.
- Text nodes: These represent the text content within elements.
- 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:
// Create an <h1> element and add it to the DOMconst newElement = document.createElement('h1');document.body.appendChild(newElement);// Get the h1 element using querySelectorconst heading = document.querySelector('h1');heading.textContent = 'Hello, DOM!';console.log(heading); // <h1>Hello, DOM!</h1>