What is the DOM?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as a tree of nodes, where each node corresponds to a part of the document (e.g., an element, attribute, or text).

Key Concepts of the DOM:

  1. Document: The entire HTML or XML document.
  2. Element: An individual HTML or XML tag.
  3. Node: A single point in the document tree. Nodes can be elements, text, comments, etc.
  4. Attributes: Properties of HTML elements (e.g., id, class).

Why is the DOM Important?

The DOM allows JavaScript to interact with and manipulate the content, structure, and style of a website dynamically. This is essential for creating interactive and dynamic web applications.

Basic Structure of the DOM

The DOM is structured as a tree of nodes. Here's a simple HTML document and its corresponding DOM tree:

HTML Document:

<!DOCTYPE html>
<html>
<head>
    <title>Document Title</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is a paragraph.</p>
</body>
</html>

Corresponding DOM Tree:

Document
└── html
    ├── head
    │   └── title
    │       └── "Document Title"
    └── body
        ├── h1
        │   └── "Hello, World!"
        └── p
            └── "This is a paragraph."

Accessing the DOM with JavaScript

JavaScript provides several methods to access and manipulate the DOM. Here are some of the most commonly used methods:

Selecting Elements

  1. document.getElementById(id): Selects an element by its id.
  2. document.getElementsByClassName(className): Selects elements by their class.
  3. document.getElementsByTagName(tagName): Selects elements by their tag name.
  4. document.querySelector(selector): Selects the first element that matches a CSS selector.
  5. document.querySelectorAll(selector): Selects all elements that match a CSS selector.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>DOM Example</title>
</head>
<body>
    <h1 id="header">Hello, World!</h1>
    <p class="text">This is a paragraph.</p>
    <p class="text">This is another paragraph.</p>

    <script>
        // Selecting an element by ID
        const header = document.getElementById('header');
        console.log(header.textContent); // Output: Hello, World!

        // Selecting elements by class name
        const paragraphs = document.getElementsByClassName('text');
        console.log(paragraphs.length); // Output: 2

        // Selecting elements by tag name
        const allParagraphs = document.getElementsByTagName('p');
        console.log(allParagraphs.length); // Output: 2

        // Selecting the first element that matches a CSS selector
        const firstParagraph = document.querySelector('.text');
        console.log(firstParagraph.textContent); // Output: This is a paragraph.

        // Selecting all elements that match a CSS selector
        const allTextElements = document.querySelectorAll('.text');
        allTextElements.forEach((element) => {
            console.log(element.textContent);
        });
        // Output:
        // This is a paragraph.
        // This is another paragraph.
    </script>
</body>
</html>

Manipulating the DOM

Once you have selected an element, you can manipulate it in various ways:

Changing Content

  • element.textContent: Gets or sets the text content of an element.
  • element.innerHTML: Gets or sets the HTML content of an element.

Changing Attributes

  • element.setAttribute(name, value): Sets the value of an attribute.
  • element.getAttribute(name): Gets the value of an attribute.
  • element.removeAttribute(name): Removes an attribute.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>DOM Manipulation Example</title>
</head>
<body>
    <h1 id="header">Hello, World!</h1>
    <p class="text">This is a paragraph.</p>

    <script>
        const header = document.getElementById('header');
        const paragraph = document.querySelector('.text');

        // Changing text content
        header.textContent = 'Welcome to the DOM!';
        console.log(header.textContent); // Output: Welcome to the DOM!

        // Changing HTML content
        paragraph.innerHTML = '<strong>This is a bold paragraph.</strong>';
        console.log(paragraph.innerHTML); // Output: <strong>This is a bold paragraph.</strong>

        // Changing attributes
        header.setAttribute('class', 'main-header');
        console.log(header.getAttribute('class')); // Output: main-header

        // Removing attributes
        header.removeAttribute('class');
        console.log(header.getAttribute('class')); // Output: null
    </script>
</body>
</html>

Practical Exercise

Task:

  1. Create an HTML file with a div element that contains an h2 heading and a p paragraph.
  2. Use JavaScript to:
    • Change the text of the h2 heading.
    • Change the HTML content of the p paragraph.
    • Add a new attribute to the div element.

Solution:

<!DOCTYPE html>
<html>
<head>
    <title>DOM Exercise</title>
</head>
<body>
    <div id="container">
        <h2>Original Heading</h2>
        <p>Original paragraph.</p>
    </div>

    <script>
        const container = document.getElementById('container');
        const heading = container.querySelector('h2');
        const paragraph = container.querySelector('p');

        // Changing the text of the h2 heading
        heading.textContent = 'Updated Heading';

        // Changing the HTML content of the p paragraph
        paragraph.innerHTML = '<em>Updated paragraph with emphasis.</em>';

        // Adding a new attribute to the div element
        container.setAttribute('data-info', 'example');

        console.log(container.outerHTML);
        // Output:
        // <div id="container" data-info="example">
        //     <h2>Updated Heading</h2>
        //     <p><em>Updated paragraph with emphasis.</em></p>
        // </div>
    </script>
</body>
</html>

Conclusion

In this lesson, you learned about the Document Object Model (DOM) and its importance in web development. You explored the basic structure of the DOM, how to access and manipulate DOM elements using JavaScript, and practiced these concepts with a practical exercise. Understanding the DOM is crucial for creating dynamic and interactive web applications. In the next lesson, you will learn how to select and manipulate DOM elements in more detail.

JavaScript: From Beginner to Advanced

Module 1: Introduction to JavaScript

Module 2: Control Structures

Module 3: Functions

Module 4: Objects and Arrays

Module 5: Advanced Objects and Functions

Module 6: The Document Object Model (DOM)

Module 7: Browser APIs and Advanced Topics

Module 8: Testing and Debugging

Module 9: Performance and Optimization

Module 10: JavaScript Frameworks and Libraries

Module 11: Final Project

© Copyright 2024. All rights reserved