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.
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
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 += `
// 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 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)
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
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
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>
`);
};
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
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
Explore these related topics:
Event delegation for dynamic elements
DOM traversal methods
Memory management in JavaScript
Advanced API error handling