DOM Introduction

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the document as a tree of objects, allowing developers to manipulate the structure, content, and styling of a webpage dynamically using JavaScript.

Key Topics

What is the DOM?

The DOM provides a structured representation of a document, enabling developers to modify its content and visual presentation. It allows access to HTML elements via JavaScript and other programming languages.

DOM Tree Representation

The DOM represents an HTML document as a tree structure, with elements like <html>, <head>, and <body> forming nodes in the tree.

<!DOCTYPE html>
<html>
    <head>
        <title>Document Tree</title>
    </head>
    <body>
        <h1>Welcome to the DOM</h1>
        <p>This is a paragraph.</p>
    </body>
</html>

Representation:

HTML (Root)

  • HEAD
    • TITLE
  • BODY
    • H1
    • P

Explanation: The HTML document is visualized as a tree structure, where each element is a node connected to its parent and sibling nodes.

Manipulating the DOM

JavaScript can dynamically modify the DOM to update content, add elements, or remove them. This enables developers to create interactive and responsive webpages.

document.getElementById("demo").textContent = "Updated Content!";

Output

(Updated content of the element with id "demo".)

Explanation: The getElementById method retrieves an element by its ID, and the textContent property updates its text dynamically.

JavaScript Usage in DOM

Below is a complete DOM example showing how to modify the content of a webpage using JavaScript.

<!DOCTYPE html>
<html>
    <head>
        <title>DOM Example</title>
    </head>
    <body>
        <p id="demo">Original Content</p>
        <button onclick="updateContent()">Click Me</button>

        <script>
            function updateContent() {
                document.getElementById("demo").textContent = "Updated Content!";
            }
        </script>
    </body>
</html>

Key Takeaways

  • DOM: A programming interface for HTML documents.
  • Tree Structure: Represents elements as nodes connected hierarchically.
  • Dynamic Updates: Use JavaScript to manipulate the DOM and update webpage content dynamically.
  • Interactive Webpages: Leverage the DOM to create responsive and interactive user experiences.