Scalable Business for Startups

Get the oars in the water and start rowing. Execution is the single biggest factor in achievement so the faster and better your execution.

+91 9472774549 thebytemind@gmail.com Looking for collaboration for your next creative project?

Chapter 10: Working with the DOM

Introduction

The Document Object Model (DOM) is an essential part of how we manipulate web pages in JavaScript. It represents the structure of an HTML document as a tree of objects, where each element, attribute, and text inside HTML is an object you can interact with through JavaScript. By learning DOM manipulation, you can create interactive, dynamic web pages that respond to user input or update automatically.

1. Understanding the DOM Structure

The DOM structure mirrors HTML document elements in a tree-like hierarchy:

  • Document: The root of the DOM tree.
  • Elements: The nodes within the tree, such as <div>, <p>, etc.
  • Attributes: Properties of elements, like class, id, or src.
  • Text: The actual content inside HTML elements.

Example DOM Tree:

  <!DOCTYPE html>
  <html>
    <head>
      <title>DOM Example</title>
    </head>
    <body>
      <div id="container">
        <h1>Hello World!</h1>
        <p>This is a paragraph.</p>
      </div>
    </body>
  </html>
2. Selecting Elements

To manipulate DOM elements, we first need to select them. JavaScript offers several methods to retrieve DOM elements based on different criteria.

Methods for Selecting Elements
  • getElementById() – Selects a single element by its unique id.
  • getElementsByClassName() – Selects all elements with a specific class.
  • getElementsByTagName() – Selects all elements with a specific tag.
  • querySelector() – Selects the first element that matches a CSS selector.
  • querySelectorAll() – Selects all elements that match a CSS selector.
Example: Selecting and Changing Text Content
  <!DOCTYPE html>
  <html>
    <body>
      <h1 id="title">Welcome</h1>
      <p class="description">This is a simple paragraph.</p>
      <script>
        // Selecting the title element by ID
        const title = document.getElementById("title");
        title.textContent = "DOM Manipulation Tutorial"; // Changes the text content

        // Selecting the paragraph by class name
        const paragraph = document.querySelector(".description");
        paragraph.textContent = "Learn how to manipulate the DOM!";
      </script>
    </body>
  </html>
3. Creating and Adding Elements

You can dynamically create new elements using document.createElement() and add them to the DOM using appendChild() or insertBefore().

Example: Adding a New Element
  <!DOCTYPE html>
  <html>
    <body>
      <div id="container"></div>
      <script>
        // Creating a new element
        const newParagraph = document.createElement("p");
        newParagraph.textContent = "This is a new paragraph added via JavaScript.";

        // Appending the new element to the container
        const container = document.getElementById("container");
        container.appendChild(newParagraph);
      </script>
    </body>
  </html>
4. Modifying Attributes

Attributes like id, class, src, href, etc., can be dynamically changed using JavaScript.

Example: Changing an Image Source
  <!DOCTYPE html>
  <html>
    <body>
      <img id="image" src="image1.jpg" alt="Image">
      <button onclick="changeImage()">Change Image</button>
      <script>
        function changeImage() {
          const image = document.getElementById("image");
          image.src = "image2.jpg"; // Changes the image source
        }
      </script>
    </body>
  </html>
5. Event Listeners

JavaScript allows you to add event listeners to elements, enabling you to respond to user actions like clicks, keypresses, or mouseovers.

Example: Handling a Button Click
  <!DOCTYPE html>
  <html>
    <body>
      <button id="greetButton">Greet</button>
      <p id="greeting"></p>
      <script>
        const button = document.getElementById("greetButton");
        button.addEventListener("click", () => {
          const greeting = document.getElementById("greeting");
          greeting.textContent = "Hello, welcome to the DOM tutorial!";
        });
      </script>
    </body>
  </html>
6. Removing Elements

To remove an element, select it and use removeChild() on its parent element or simply remove() on the element itself.

Example: Removing an Element
  <!DOCTYPE html>
  <html>
    <body>
      <p id="removeThis">This paragraph will be removed.</p>
      <button onclick="removeParagraph()">Remove Paragraph</button>
      <script>
        function removeParagraph() {
          const paragraph = document.getElementById("removeThis");
          paragraph.remove(); // Removes the element from the DOM
        }
      </script>
    </body>
  </html>
7. Modifying Styles

You can dynamically change the style of elements using the style property or by adding/removing CSS classes.

Example: Changing Styles Dynamically
  <!DOCTYPE html>
  <html>
    <body>
      <button id="changeColor">Change Color</button>
      <div id="colorBox" style="width: 100px; height: 100px; background-color: blue;"></div>
      <script>
        const button = document.getElementById("changeColor");
        button.addEventListener("click", () => {
          const colorBox = document.getElementById("colorBox");
          colorBox.style.backgroundColor = "green"; // Changes the background color
        });
      </script>
    </body>
  </html>
Summary

In this chapter, you learned:

  • How to navigate and understand the DOM structure.
  • Selecting elements and manipulating their content and attributes.
  • Dynamically adding and removing elements.
  • Handling events and applying CSS styles.

Mastering DOM manipulation is key to creating interactive web pages. Practice these methods to build dynamic features and handle user interactions effectively.