JavaScript Intermediate

JavaScript DOM Manipulation: Interacting with Web Pages

CodingerWeb
CodingerWeb
20 views 70 min read

Understanding the DOM

The Document Object Model (DOM) represents the structure of HTML documents. JavaScript can interact with and modify the DOM to create dynamic web pages.

What is the DOM?

The DOM is a tree-like representation of your HTML document that JavaScript can access and modify:

// HTML structure becomes a DOM tree
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1 id="title">Welcome</h1>
    <p class="intro">This is a paragraph.</p>
  </body>
</html>

Selecting Elements

// Select by ID
let title = document.getElementById("title");
console.log(title);

// Select by class name
let intro = document.getElementsByClassName("intro")[0];
console.log(intro);

// Select by tag name
let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs);

// Modern selectors (recommended)
let titleModern = document.querySelector("#title");        // ID
let introModern = document.querySelector(".intro");        // Class
let firstP = document.querySelector("p");                  // First p tag
let allPs = document.querySelectorAll("p");               // All p tags

Modifying Element Content

// HTML for examples
<div id="content">
    <h2>Original Title</h2>
    <p>Original paragraph</p>
</div>

// Change text content
let heading = document.querySelector("h2");
heading.textContent = "New Title";

// Change HTML content
let content = document.getElementById("content");
content.innerHTML = "<h2>Updated Title</h2><p>Updated paragraph with <strong>bold text</strong></p>";

// Get content
console.log(heading.textContent);  // Gets text only
console.log(content.innerHTML);    // Gets HTML markup

Modifying Element Attributes

// HTML example
<img id="myImage" src="old-image.jpg" alt="Old image">
<a id="myLink" href="https://example.com">Click here</a>

// Get attributes
let image = document.getElementById("myImage");
console.log(image.getAttribute("src"));

// Set attributes
image.setAttribute("src", "new-image.jpg");
image.setAttribute("alt", "New image");

// Direct property access (for common attributes)
let link = document.getElementById("myLink");
link.href = "https://google.com";
link.textContent = "Go to Google";

// Remove attributes
image.removeAttribute("alt");

Modifying CSS Styles

// HTML example
<div id="box">This is a box</div>

let box = document.getElementById("box");

// Individual style properties
box.style.backgroundColor = "blue";
box.style.color = "white";
box.style.padding = "20px";
box.style.borderRadius = "10px";

// Multiple styles at once
box.style.cssText = "background-color: red; color: white; padding: 15px; margin: 10px;";

// Add/remove CSS classes
box.classList.add("highlight");
box.classList.remove("old-style");
box.classList.toggle("active");  // Add if not present, remove if present

// Check if class exists
if (box.classList.contains("highlight")) {
    console.log("Box is highlighted");
}

Creating and Adding Elements

// Create new elements
let newDiv = document.createElement("div");
let newParagraph = document.createElement("p");
let newButton = document.createElement("button");

// Set content and attributes
newDiv.textContent = "This is a new div";
newDiv.className = "new-element";

newParagraph.innerHTML = "This is a <strong>new paragraph</strong>";

newButton.textContent = "Click me!";
newButton.id = "dynamic-button";

// Add to the page
document.body.appendChild(newDiv);
newDiv.appendChild(newParagraph);
newDiv.appendChild(newButton);

// Insert at specific position
let container = document.getElementById("container");
let firstChild = container.firstElementChild;
container.insertBefore(newDiv, firstChild);  // Insert before first child

Removing Elements

// Remove element
let elementToRemove = document.getElementById("old-element");
if (elementToRemove) {
    elementToRemove.remove();  // Modern way
    // elementToRemove.parentNode.removeChild(elementToRemove);  // Older way
}

// Remove all children
let container = document.getElementById("container");
container.innerHTML = "";  // Quick way
// Or loop through and remove each child

Event Handling

// HTML example
<button id="clickBtn">Click Me</button>
<input id="textInput" type="text" placeholder="Type something">

// Add event listeners
let button = document.getElementById("clickBtn");
button.addEventListener("click", function() {
    alert("Button was clicked!");
});

// Arrow function syntax
button.addEventListener("click", () => {
    console.log("Button clicked with arrow function");
});

// Event with parameters
let input = document.getElementById("textInput");
input.addEventListener("input", function(event) {
    console.log("Input value:", event.target.value);
});

// Multiple event types
function handleMouseEvents(event) {
    console.log(`Mouse event: ${event.type}`);
}

button.addEventListener("mouseenter", handleMouseEvents);
button.addEventListener("mouseleave", handleMouseEvents);

// Remove event listener
button.removeEventListener("click", handleMouseEvents);

Form Handling

// HTML form
<form id="userForm">
    <input type="text" id="username" placeholder="Username" required>
    <input type="email" id="email" placeholder="Email" required>
    <button type="submit">Submit</button>
</form>

// Handle form submission
let form = document.getElementById("userForm");
form.addEventListener("submit", function(event) {
    event.preventDefault();  // Prevent default form submission
    
    // Get form data
    let username = document.getElementById("username").value;
    let email = document.getElementById("email").value;
    
    // Validate
    if (username.length < 3) {
        alert("Username must be at least 3 characters");
        return;
    }
    
    // Process data
    console.log("Form submitted:", { username, email });
    
    // Reset form
    form.reset();
});

Practical Examples

// Example 1: Dynamic list
function createTodoList() {
    let container = document.createElement("div");
    container.innerHTML = `
        <h3>Todo List</h3>
        <input type="text" id="todoInput" placeholder="Add new task">
        <button id="addBtn">Add Task</button>
        <ul id="todoList"></ul>
    `;
    
    document.body.appendChild(container);
    
    let input = document.getElementById("todoInput");
    let addBtn = document.getElementById("addBtn");
    let list = document.getElementById("todoList");
    
    function addTask() {
        let taskText = input.value.trim();
        if (taskText === "") return;
        
        let li = document.createElement("li");
        li.innerHTML = `
            ${taskText}
            <button onclick="this.parentElement.remove()">Delete</button>
        `;
        
        list.appendChild(li);
        input.value = "";
    }
    
    addBtn.addEventListener("click", addTask);
    input.addEventListener("keypress", function(e) {
        if (e.key === "Enter") addTask();
    });
}

// Example 2: Image gallery
function createImageGallery() {
    let images = [
        "image1.jpg",
        "image2.jpg", 
        "image3.jpg"
    ];
    
    let gallery = document.createElement("div");
    gallery.className = "gallery";
    
    images.forEach((src, index) => {
        let img = document.createElement("img");
        img.src = src;
        img.alt = `Image ${index + 1}`;
        img.style.width = "200px";
        img.style.margin = "10px";
        img.style.cursor = "pointer";
        
        img.addEventListener("click", function() {
            // Create modal or enlarge image
            alert(`Clicked on ${this.alt}`);
        });
        
        gallery.appendChild(img);
    });
    
    document.body.appendChild(gallery);
}

// Call the functions to create the examples
createTodoList();
createImageGallery();