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.
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:
The DOM tree for this document would look like this:
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: