top of page
  • Writer's pictureRajesh Dhiman

Chapter 5: The DOM and Browser Interaction

In this chapter, you'll learn about the Document Object Model (DOM) and how JavaScript can be used to interact with web pages. Understanding the DOM is crucial for creating dynamic and interactive web applications.


What is the DOM?


The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects, allowing JavaScript to interact with and manipulate HTML elements dynamically. Understanding the DOM is crucial for building interactive and dynamic web applications.


Key Concepts:

  • Nodes and Elements:

  • Nodes are the building blocks of the DOM. There are several types of nodes, including element nodes, text nodes, and attribute nodes.

  • Element nodes represent HTML tags and are the most commonly manipulated nodes in the DOM.

  • Tree Structure:

  • The DOM represents a document as a tree structure, where the root is the <html> element, and each element is a child of its parent element.

  • This hierarchical structure allows for traversing and manipulating elements in the document.

  • DOM API:

  • The DOM provides a set of APIs (methods and properties) for interacting with the document. These APIs allow you to select, create, and modify elements.


Selecting and Manipulating DOM Elements


JavaScript provides several methods for selecting and manipulating DOM elements. Understanding how to work with these methods is essential for creating dynamic web pages.


Selecting Elements:

  • getElementById(): Selects an element by its unique id attribute.


  const title = document.getElementById("main-title");

  console.log(title.innerText);


  • getElementsByClassName(): Selects elements by their class name, returning a live HTMLCollection.


  const items = document.getElementsByClassName("item");

  console.log(items.length);


  • getElementsByTagName(): Selects elements by their tag name, returning a live HTMLCollection.


  const paragraphs = document.getElementsByTagName("p");

  console.log(paragraphs.length);


  • querySelector(): Selects the first element that matches a CSS selector.


  const firstItem = document.querySelector(".item");

  console.log(firstItem.innerText);


  • querySelectorAll(): Selects all elements that match a CSS selector, returning a static NodeList.


  const allItems = document.querySelectorAll(".item");

  console.log(allItems.length);

Manipulating Elements:


Once an element is selected, you can manipulate its content, attributes, and styles.

  • Modify Content:


  title.innerText = "Updated Title";

  title.innerHTML = "<strong>Updated</strong> Title";


  • Modify Attributes:


  const link = document.querySelector("a");

  link.setAttribute("href", "https://example.com");

  link.href = "https://example.com";


  • Modify Styles:


  title.style.color = "blue";

  title.style.fontSize = "24px";


  • Add and Remove Classes:


  title.classList.add("highlight");

  title.classList.remove("highlight");


  • Create and Append Elements:


  const newItem = document.createElement("li");

  newItem.innerText = "New Item";

  document.querySelector("ul").appendChild(newItem);

Event Handling and User Interaction


Events are actions or occurrences that happen in the browser, such as clicks, form submissions, and keyboard input. JavaScript can listen for these events and execute code in response.


Adding Event Listeners:


You can attach event listeners to elements to respond to user interactions.

  • Basic Event Listener:


  const button = document.querySelector("button");

  button.addEventListener("click", function() {

    alert("Button clicked!");

  });


  • Named Function as Event Listener:


  function handleClick() {

    alert("Button clicked!");

  }


  button.addEventListener("click", handleClick);


  • Removing Event Listeners:


  button.removeEventListener("click", handleClick);

Common Events:

  • Mouse Events: click, dblclick, mouseover, mouseout, mousedown, mouseup

  • Keyboard Events: keydown, keyup, keypress

  • Form Events: submit, change, focus, blur

  • Window Events: load, resize, scroll


Event Object:


The event object contains information about the event and can be used to access event-specific data.


button.addEventListener("click", function(event) {

  console.log("Mouse X:", event.clientX);

  console.log("Mouse Y:", event.clientY);

});

Event Delegation:


Event delegation is a technique where a single event listener is attached to a parent element to manage events for its child elements. This is useful for handling events on dynamically added elements.


const list = document.querySelector("ul");


list.addEventListener("click", function(event) {

  if (event.target.tagName === "LI") {

    console.log("Item clicked:", event.target.innerText);

  }

});




FAQs

  • What is the DOM in JavaScript?The DOM (Document Object Model) is a programming interface for web documents, representing the structure of a document as a tree of objects. It allows JavaScript to interact with and manipulate HTML elements.

  • How do you select an element with a specific ID in the DOM?You can use document.getElementById("id") to select an element with a specific ID.

  • What is the difference between querySelector() and querySelectorAll()?querySelector() selects the first element that matches a CSS selector, while querySelectorAll() selects all elements that match the selector, returning a static NodeList.

  • How do you add an event listener to an element?You can use element.addEventListener("event", function) to attach an event listener to an element.

  • What is event delegation, and why is it useful?Event delegation is a technique where a single event listener is attached to a parent element to manage events for its child elements. It is useful for handling events on dynamically added elements and improving performance by reducing the number of event listeners.


Questions

  1. How do you change the text content of an element with the ID title?

  2. Using document.getElementById("title").innerText = "New Title"

  3. What method would you use to create a new DOM element?

  4. document.createElement("tagName")

  5. How can you prevent the default behavior of an event?

  6. By calling event.preventDefault() within the event handler.

  7. What is the output of the following code?

  1. const items = document.querySelectorAll(".item");

  2. items.forEach(item => item.classList.add("active"));

  3. console.log(items.length);


  1. The number of elements with the class item.

  2. **How do you remove


an event listener from an element?**

  • Using element.removeEventListener("event", function)


Real-World Coding Problems

  • Problem 1: Dynamic List


Create a dynamic list where users can add and remove items. Implement functions to add a new item to the list and remove an item when it is clicked.


  <input type="text" id="item-input" placeholder="Add an item">

  <button id="add-button">Add</button>

  <ul id="item-list"></ul>


  <script>

    const input = document.getElementById("item-input");

    const addButton = document.getElementById("add-button");

    const itemList = document.getElementById("item-list");


    addButton.addEventListener("click", function() {

      const newItemText = input.value;

      if (newItemText) {

        const newItem = document.createElement("li");

        newItem.innerText = newItemText;

        itemList.appendChild(newItem);

        input.value = "";

      }

    });


    itemList.addEventListener("click", function(event) {

      if (event.target.tagName === "LI") {

        itemList.removeChild(event.target);

      }

    });

  </script>

Challenge: Add a confirmation dialog before removing an item from the list.

  • Problem 2: Image Gallery


Create an image gallery with thumbnail images. When a thumbnail is clicked, display the larger version of the image above the thumbnails.


  <div id="gallery">

    <img id="main-image" src="image1.jpg" alt="Main Image">

    <div id="thumbnails">

      <img src="thumb1.jpg" data-large="image1.jpg" alt="Thumbnail 1">

      <img src="thumb2.jpg" data-large="image2.jpg" alt="Thumbnail 2">

      <img src="thumb3.jpg" data-large="image3.jpg" alt="Thumbnail 3">

    </div>

  </div>


  <script>

    const mainImage = document.getElementById("main-image");

    const thumbnails = document.getElementById("thumbnails");


    thumbnails.addEventListener("click", function(event) {

      if (event.target.tagName === "IMG") {

        const largeImageSrc = event.target.getAttribute("data-large");

        mainImage.src = largeImageSrc;

      }

    });

  </script>

Challenge: Add a caption below the main image that updates with each image change.

  • Problem 3: Form Validation


Create a form with input fields for name and email. Add validation to ensure that the fields are not empty and that the email field contains a valid email address. Display error messages if the validation fails.


  <form id="contact-form">

    <input type="text" id="name" placeholder="Name">

    <input type="email" id="email" placeholder="Email">

    <button type="submit">Submit</button>

    <div id="error-message"></div>

  </form>


  <script>

    const form = document.getElementById("contact-form");

    const nameInput = document.getElementById("name");

    const emailInput = document.getElementById("email");

    const errorMessage = document.getElementById("error-message");


    form.addEventListener("submit", function(event) {

      event.preventDefault();


      const name = nameInput.value.trim();

      const email = emailInput.value.trim();

      let errors = [];


      if (!name) {

        errors.push("Name is required.");

      }


      if (!email) {

        errors.push("Email is required.");

      } else if (!/^\S+@\S+\.\S+$/.test(email)) {

        errors.push("Email is invalid.");

      }


      if (errors.length > 0) {

        errorMessage.innerText = errors.join(" ");

      } else {

        errorMessage.innerText = "";

        alert("Form submitted successfully!");

        form.reset();

      }

    });

  </script>

Challenge: Add real-time validation to highlight errors as the user types.

0 views0 comments

Recent Posts

See All

Comments


bottom of page