What data structure is used to represent the DOM?

JavaScriptMeta

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)

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)
00:00