What data structure is used to represent the DOM?
Data structure of DOM
The Document Object Model (DOM) is represented using a tree data structure, specifically a type of tree called a node tree. This representation is fundamental to how web browsers interpret and render HTML documents.
Understanding the DOM Tree π²
When a browser loads an HTML document, it parses the markup and creates a hierarchical tree-like structure in memory. This tree has several key characteristics:
-
Node-based hierarchy: Every element in an HTML document becomes a node in this tree.
-
Parent-child relationships: Elements nested inside other elements establish parent-child relationships in the tree.
-
Tree root: The entire structure begins with a root node, which is the document object.
-
Different node types: The DOM tree contains various types of nodes, including:
- Element nodes (representing HTML tags like
<div>,<p>, etc.) - Text nodes (containing the text between tags)
- Attribute nodes (representing element attributes)
- Comment nodes (for HTML comments)
- Document nodes (the root of the tree)
- Element nodes (representing HTML tags like
Visualizing the DOM Tree π²
Consider this simple HTML
<!DOCTYPE html><html><head><title>Sample Page</title></head><body><h1>Hello World</h1><div><p>This is a paragraph.</p></div></body></html>
The corresponding DOM tree would look like
document (document node)βββ html (element node)βββ head (element node)β βββ title (element node)β βββ "Sample Page" (text node)βββ body (element node)βββ h1 (element node)β βββ "Hello World" (text node)βββ div (element node)βββ p (element node)βββ "This is a paragraph." (text node)
Related JavaScript interview topics
Continue with nearby questions from the same topic cluster.