Lesson 4: Manipulating the DOM

The DOM (Document Object Model) is the interface that allows JavaScript to interact with and manipulate the structure, content, and style of a web page. When a web page is loaded in a browser, the browser converts the HTML and CSS into the DOM, enabling JavaScript to make dynamic changes to the page.


Accessing Elements

getElementById:

let header = document.getElementById('header');

querySelector:

let paragraph = document.querySelector('p');

Changing Content

let title = document.getElementById('title');
title.textContent = 'Updated Title';

Changing Styles

let button = document.querySelector('button');
button.style.backgroundColor = 'blue';

Why is the DOM Important?

The DOM allows web pages to be:

  • Dynamic: Content, structure, and styles can change after the page has loaded.
  • Interactive: Respond to user inputs like clicks, form submissions, or mouse movements.
  • Efficient: Update only parts of a page instead of reloading the entire page.

Complete Example

Here’s a complete example of how to manipulate the DOM in JavaScript, showcasing some of the most common techniques such as selecting elements, modifying their content, changing styles, and responding to user interactions.


HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Manipulation Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }
        #dynamic-text {
            font-size: 1.5rem;
            color: blue;
            margin: 20px 0;
        }
        .color-box {
            width: 100px;
            height: 100px;
            margin: 10px auto;
            background-color: lightgray;
            border: 1px solid #ccc;
        }
        button {
            padding: 10px 20px;
            font-size: 1rem;
        }
    </style>
</head>
<body>
    <h1>DOM Manipulation Example</h1>
    <p id="dynamic-text">Click the button to change this text.</p>
    <div class="color-box"></div>
    <button id="change-btn">Change Text & Color</button>
    <script src="script.js"></script>
</body>
</html>

JavaScript Code (script.js)

// Select elements
const textElement = document.getElementById('dynamic-text');
const colorBox = document.querySelector('.color-box');
const changeButton = document.getElementById('change-btn');

// Add an event listener to the button
changeButton.addEventListener('click', () => {
    // Change the text content of the paragraph
    textElement.textContent = 'The text has been updated!';
    
    // Change the text color
    textElement.style.color = 'green';
    
    // Update the background color of the box
    const randomColor = getRandomColor();
    colorBox.style.backgroundColor = randomColor;
    
    // Add a border to the box
    colorBox.style.border = '3px solid black';
});

// Helper function to generate a random color
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

How It Works

  1. The button (#change-btn) is selected using getElementById.
  2. When the button is clicked, the text of the paragraph (#dynamic-text) is updated using textContent, and its color is changed using style.color.
  3. The background color of the .color-box div is updated to a random color generated by the getRandomColor function.
  4. Additional styling is applied to the .color-box, like adding a thicker border.

Expected Behavior

  1. When you first load the page, it will display a paragraph, a gray box, and a button.
  2. Clicking the button will:
    • Update the text in the paragraph.
    • Change the text color of the paragraph to green.
    • Set the .color-box background to a random color.
    • Add a thick black border around the box.

This example demonstrates the basics of DOM manipulation, styling, and interaction.