无法向另一个Div追加Div的技术求助:解决Uncaught (in promise) TypeError: document.getElementsByClassName(...).appendChild is not a function错误
appendChild is not a function Error in Your Gallery Code Hey there, let's break down what's causing that error and get your image gallery working properly.
The Root Cause of the Error
The error Uncaught (in promise) TypeError: document.getElementsByClassName(...).appendChild is not a function happens because:
document.getElementsByClassName()returns an HTMLCollection (a collection of elements, even if there's only one matching element on the page). This is a list-like object, not a single DOM element, so it doesn't have theappendChild()method.- You're repeating
document.getElementsByClassName("gallery")multiple times instead of storing the element reference once, which is inefficient and prone to this exact issue.
Step-by-Step Fixes
1. Correctly Get the Gallery Element
Replace all instances of document.getElementsByClassName("gallery") with either:
document.querySelector(".gallery")(returns the first matching element, perfect since you only have one gallery)- Or if you stick with
getElementsByClassName, grab the first element in the collection:document.getElementsByClassName("gallery")[0]
2. Fix the Fetch Template String
Your fetch URL uses double quotes ("https://api.pexels.com/v1/curated?per_page=${pageOne}"), which won't parse the ${pageOne} variable. You need to use backticks ` for template strings to interpolate variables.
3. Optimize Element Selections
Use querySelector for other elements too to avoid HTMLCollection issues:
- Replace
document.getElementsByClassName("next")withdocument.querySelector(".next") - Replace
document.getElementsByClassName("searchBar")withdocument.querySelector(".searchBar")
4. Add Search Button Functionality
Your current code listens for input changes but doesn't handle the search button click. Let's add that to trigger a search instead of showing curated photos.
5. Avoid Duplicate Images
When loading new pages or searching, clear the gallery first so you don't append new photos on top of old ones.
Fixed Full Code
JavaScript
const auth = "563492ad6f917000010000018130a0db31044cd6b83e19c30395d9e1"; const input = document.querySelector("input"); const nextBtn = document.querySelector(".next"); const gallery = document.querySelector(".gallery"); const searchBtn = document.querySelector(".searchBar button"); let page = 1; let search = false; let query = ""; // Handle input changes input.addEventListener("input", (e) => { query = e.target.value.trim(); }); // Handle search button click searchBtn.addEventListener("click", async () => { if (!query) return; // Don't search if input is empty search = true; page = 1; // Reset to first page for new search gallery.innerHTML = ""; // Clear existing photos await createPhotos(page); }); // Handle next page button click nextBtn.addEventListener("click", async () => { page++; await createPhotos(page); }); async function createPhotos(pageNum) { let url; if (search) { url = `https://api.pexels.com/v1/search?query=${query}&per_page=15&page=${pageNum}`; } else { url = `https://api.pexels.com/v1/curated?per_page=15&page=${pageNum}`; } try { const data = await fetch(url, { method: "GET", headers: { Accept: "application/json", Authorization: auth, }, }); if (!data.ok) throw new Error(`HTTP error! Status: ${data.status}`); const result = await data.json(); result.photos.forEach((photo) => { const pic = document.createElement("div"); pic.innerHTML = `<img src="${photo.src.large}" alt="${photo.photographer}" />`; gallery.appendChild(pic); }); } catch (err) { console.error("Failed to fetch photos:", err); } } // Initialize with curated photos createPhotos(page);
HTML
<div class="container"> <div class="searchBar"> <input type="text" placeholder="Search for photos..." /> <button type="button">Search</button> </div> <div class="gallery"></div> <div class='next'>Next Page</div> </div>
Additional Notes
- Added error handling with
try/catchto catch fetch failures (like network issues or invalid API keys). - Added
alttext to images for accessibility. - Set a reasonable
per_pagevalue (15) instead of using the page number directly (your original code usedper_page=${pageOne}, which would load 1 photo on page 1, 2 on page 2, etc.—probably not what you wanted). - Trimmed the input query to avoid searching for empty strings.
内容的提问来源于stack exchange,提问作者Babilon

