Create and Remove Elements Practice

Understanding the Problem

We need to build an interactive dog gallery where users can:

Add new random dog images by fetching from an API

Remove the first dog image in the gallery

Remove the last dog image in the gallery

Think of this like managing a physical photo album where you can add new photos at the end and remove photos from either the beginning or end.

Devising a Plan

1. Study the API response structure from dog.ceo

2. Parse breed name from image URL

3. Create DOM elements for new dog cards

4. Implement removal functionality

5. Add error handling for API requests

Carrying Out the Plan

Here's our solution with detailed explanations:

/****************************** ADD DOG BUTTON ******************************/
const add = document.getElementById("add");
add.addEventListener("click", async () => {
    try {
        const res = await fetch("https://dog.ceo/api/breeds/image/random")
        const data = await res.json();

        const url = data.message; // URL of new dog image

        /*--------------- Get breed (Hint: Parse from URL) ---------------- */

        const breed = url.split('/')[4];


        /*------------ Create new dog card with the url above ------------- */
        /* (use the HTML structure for the current dog image in the index.html
            file to create a new image with the url) */

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

        const newFigure = document.createElement("figure");

        const newImg = document.createElement("img");
        newImg.src = url;

        const newCaption = document.createElement("figcaption");
        newCaption.innerText = breed;

        newFigure.appendChild(newImg);
        newFigure.appendChild(newCaption);

        newDog.appendChild(newFigure);


        /* Add the new dog card as a child to the ul in the .gallery element */

        const ul = document.getElementsByTagName("ul")[0];
        ul.appendChild(newDog);

        // other way of doing it but unsafe, should not use:
        // ul.innerHTML += `
        //     
  • //
    // //
    ${breed}
    //
    //
  • // `; } catch (e) { console.log("Couldn't fetch dog :(") } }); /************************** REMOVE FIRST DOG BUTTON **************************/ const removeFirst = document.getElementById("remove-first"); removeFirst.addEventListener("click", () => { /*-------------------- Select the first dog card --------------------- */ const firstDog = document.querySelector("li"); /*-------------------- Remove the first dog card --------------------- */ if (firstDog) { firstDog.remove(); } else { console.log("No dogs left!! :(") } }); /************************** REMOVE LAST DOG BUTTON ***************************/ const removeLast = document.getElementById("remove-last"); removeLast.addEventListener("click", () => { /*-------------------- Select the last dog card ----------------------- */ const allDogs = document.querySelectorAll("li"); let lastDog; if(allDogs.length > 0) { lastDog = allDogs[allDogs.length - 1]; } // OR: // const lastDog = document.querySelectorAll("li:last-child"); /*-------------------- Remove the last dog card ----------------------- */ if (lastDog) { lastDog.remove(); } else { console.log("No dogs left!! :(") } });

    Understanding the Solution

    The Photo Album Analogy

    Think of this code like managing a digital photo album:

    Adding a photo (createElement) is like getting a new photo and frame

    Setting attributes (src, textContent) is like writing details on the back

    Appending elements (appendChild) is like placing photos in the album

    Removing elements (remove) is like taking photos out of the album

    Creating Elements Step by Step

    Creating DOM elements follows a pattern similar to building something with LEGO blocks:

    1. Create each piece (createElement)

    2. Customize each piece (setting attributes)

    3. Connect the pieces (appendChild)

    4. Place the finished structure (appendChild to gallery)

    DOM Tree Navigation

    Finding elements in the DOM is like following a family tree:

    querySelector finds specific elements like looking up someone by name

    parentElement is like finding someone's parent

    children is like listing someone's children

    lastElementChild is like identifying the youngest child

    Real-World Applications

    These DOM manipulation skills are used in many common web features:

    Social media feeds that load new content

    Shopping carts that add and remove items

    Comment systems that add new comments

    Photo galleries and portfolios

    Alternative Approaches

    Here's a more advanced solution using template literals:

    // Alternative solution using template literals
    const addDogCard = (url, breed) => {
        const gallery = document.querySelector('.gallery ul');
        gallery.insertAdjacentHTML('beforeend', `
            <li>
                <figure>
                    <img src="${url}" />
                    <figcaption>${breed}</figcaption>
                </figure>
            </li>
        `);
    };
        

    Common Pitfalls and Solutions

    Always check if elements exist before removing them

    Remember to handle API errors gracefully

    Be careful with URL parsing - validate the structure

    Consider memory management for large galleries

    Practice Exercises

    Try these modifications to deepen your understanding:

    Add a "remove by click" feature for individual dogs

    Implement a loading spinner while fetching

    Add breed filtering functionality

    Create an undo feature for removals

    Further Learning

    Explore these related topics:

    Event delegation for dynamic elements

    DOM traversal methods

    Memory management in JavaScript

    Advanced API error handling