Day 5: Introduction to the DOM - Manipulating the Web with JavaScript

Day 5: Introduction to the DOM - Manipulating the Web with JavaScript

Exploring the DOM - Bringing Interactivity to Your Web Pages”

Introduction:

Explain the Document Object Model (DOM) as the bridge between HTML/CSS and JavaScript, enabling developers to dynamically interact with and manipulate web pages.

Example:

"The DOM is your JavaScript’s playground, where HTML elements become objects you can control. Today, we’ll learn how to access, manipulate, and add interactivity to web pages using JavaScript and the DOM."


Main Content:

  1. What is the DOM?

    • A tree-like structure representing the HTML of a webpage.

    • Relationship between nodes (parent, child, sibling).

  2. Accessing DOM Elements:

    • Methods for selecting elements:

        // By ID  
        const header = document.getElementById('header');  
      
        // By class  
        const buttons = document.getElementsByClassName('btn');  
      
        // By query selector  
        const firstButton = document.querySelector('.btn');  
        const allButtons = document.querySelectorAll('.btn');
      
  3. Manipulating DOM Elements:

    • Changing text content:

        header.textContent = 'Welcome to Day 5!';
      
    • Changing styles:

        header.style.color = 'blue';  
        header.style.fontSize = '2em';
      
    • Adding/removing classes:

        header.classList.add('highlight');  
        header.classList.remove('highlight');
      
  4. Handling Events:

    • Example of a button click event:

        const button = document.querySelector('.btn');  
        button.addEventListener('click', () => {  
            alert('Button clicked!');  
        });
      
  5. Practical Example:

    • Create a simple webpage with a button that changes the text and style of a header when clicked:

        <h1 id="header">Hello, DOM!</h1>  
        <button class="btn">Click Me</button>  
        <script>  
            const header = document.getElementById('header');  
            const button = document.querySelector('.btn');  
            button.addEventListener('click', () => {  
                header.textContent = 'You clicked the button!';  
                header.style.color = 'green';  
            });  
        </script>
      

Practical Task for Readers:

  • Build a webpage with:

    1. A button that changes the background color of the page when clicked.

    2. An input field where users can type their name and display it dynamically below the input.


Conclusion:

  • Recap the importance of the DOM in enabling dynamic content updates.

  • Encourage readers to experiment with DOM methods and events.

  • Tease Day 6: "Tomorrow, we’ll dive deeper into events and explore event delegation."