16.2 DOM Selection Methods (20 mins)

  1. Introduction to DOM Selection Methods:

    • DOM selection methods allow you to access and manipulate HTML elements in a web page using JavaScript. The most common methods include:

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

      • getElementsByClassName(): Selects all elements with a specified class name.

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

  2. DOM Selection Methods:

    • getElementById():

      • Use Case: Used to select a single element by its unique id. The id attribute should be unique within the document.

      • Syntax: document.getElementById("id")

      • Example:

        <h1 id="title">Hello, World!</h1>
        <script>
          let heading = document.getElementById("title");
          console.log(heading);  // Outputs: <h1 id="title">Hello, World!</h1>
        </script>
    • getElementsByClassName():

      • Use Case: Used to select multiple elements that share the same class name. It returns a live HTMLCollection, which is similar to an array but cannot use all array methods.

      • Syntax: document.getElementsByClassName("className")

      • Example:

        <p class="text">First paragraph</p>
        <p class="text">Second paragraph</p>
        <script>
          let paragraphs = document.getElementsByClassName("text");
          console.log(paragraphs);  // Outputs: HTMLCollection of paragraphs
          console.log(paragraphs[0].innerText);  // Outputs: First paragraph
        </script>
    • querySelector():

      • Use Case: Used to select the first element that matches a CSS selector. You can select by id, class, or any CSS selector.

      • Syntax: document.querySelector("CSS selector")

      • Example:

        <h1 id="main-heading">Main Heading</h1>
        <p class="description">This is a description.</p>
        <script>
          let heading = document.querySelector("#main-heading");
          let description = document.querySelector(".description");
          console.log(heading);  // Outputs: <h1 id="main-heading">Main Heading</h1>
          console.log(description);  // Outputs: <p class="description">This is a description.</p>
        </script>

Student Activity (20 mins):

Objective: Students will explore how to select and manipulate DOM elements using getElementById(), getElementsByClassName(), and querySelector().


Step-by-Step Activity:

  1. Create an HTML file (e.g., dom_selection_methods.html) and write JavaScript code to demonstrate the use of different DOM selection methods.

  2. Example Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>DOM Selection Methods</title>
    </head>
    <body>
      <h1 id="main-title">Welcome to DOM Selection</h1>
      <p class="content">This is the first paragraph.</p>
      <p class="content">This is the second paragraph.</p>
      <p class="info">This is additional information.</p>
    
      <script>
        // 1. getElementById() - Select and modify an element by its ID
        let title = document.getElementById("main-title");
        console.log("Title:", title);  // Outputs: <h1 id="main-title">Welcome to DOM Selection</h1>
        title.innerText = "DOM Selection Methods";  // Change the text
    
        // 2. getElementsByClassName() - Select all elements with the class "content"
        let contentParagraphs = document.getElementsByClassName("content");
        console.log("Content Paragraphs:", contentParagraphs);  // Outputs: HTMLCollection
        contentParagraphs[1].style.color = "blue";  // Change color of second paragraph
    
        // 3. querySelector() - Select the first element that matches a CSS selector
        let infoParagraph = document.querySelector(".info");
        console.log("Info Paragraph:", infoParagraph);  // Outputs: <p class="info">This is additional information.</p>
        infoParagraph.style.fontWeight = "bold";  // Make the text bold
      </script>
    </body>
    </html>
  3. Run the file in a browser:

    • Open the HTML file in a browser and observe how the elements are selected and modified using different DOM selection methods.

    • Use Developer Tools (F12 or right-click and select Inspect > Console) to view the logged DOM elements.


Explanation of the Code:

  • getElementById(): The script selects the <h1> element with the id="main-title" and changes its text to "DOM Selection Methods".

  • getElementsByClassName(): The script selects all elements with the class content and changes the color of the second paragraph to blue.

  • querySelector(): The script selects the first element with the class info and changes its font to bold.


Challenge:

  1. Modify the DOM Elements:

    • Add a button to the page that changes the background color of all paragraphs with the class content when clicked.

    Example:

    <button id="changeColorButton">Change Background Color</button>
    
    <script>
      let button = document.getElementById("changeColorButton");
      button.addEventListener("click", function() {
        for (let i = 0; i < contentParagraphs.length; i++) {
          contentParagraphs[i].style.backgroundColor = "lightgray";
        }
      });
    </script>
  2. Extra Challenge:

    • Use querySelectorAll() to select all elements that match a CSS selector (like all paragraphs) and change their style dynamically.

    Example:

    let allParagraphs = document.querySelectorAll("p");
    allParagraphs.forEach(function(paragraph) {
      paragraph.style.fontSize = "18px";
    });

Activity Follow-up Questions:

  1. What is the difference between getElementById() and querySelector() when selecting elements?

  2. How does getElementsByClassName() behave differently from querySelectorAll()?

  3. Can you think of a scenario where selecting multiple elements would be necessary?


Expected Outcome:

Students will:

  • Understand how to use getElementById(), getElementsByClassName(), and querySelector() to select and manipulate elements in the DOM.

  • Practice selecting individual and multiple elements and modifying their styles or content.

  • Explore how JavaScript can dynamically change a webpage’s structure and appearance using DOM selection methods.

Last updated