1

i'm trying to display my picture to my gallery div but the console shows the mistake as "uncaught (in promise) TypeError: document.getElementsByClassName(...).appendChild is not a function". I don't know what's wrong, please help me! Thank you so much!

const auth = "563492ad6f917000010000018130a0db31044cd6b83e19c30395d9e1"
const input = document.querySelector("input")
const nextBtn = document.getElementsByClassName("next")
const gallery = document.getElementsByClassName("gallery")
const searchBar = document.getElementsByClassName("searchBar")

let pageOne = 1;
let search = false;
let query = "";

input.addEventListener("input", (e) => {
  e.preventDefault()
  query = e.target.value

})

async function createPhotos(pageOne) {
  const data = await fetch("https://api.pexels.com/v1/curated?per_page=${pageOne}", {
    method: "GET",
    headers: {
      Accept: "application.json",
      Authorization: auth
    }
  })
  
  const result = await data.json()
  
  result.photos.forEach((photo) => {
    const pic = document.createElement("div")
    pic.innerHTML = `<img src=${photo.src.large}/ >`
    document.getElementsByClassName("gallery").appendChild(pic)
  })
}
createPhotos(pageOne)
<div class="container">
  <div class="searchBar">
    <input type="text" />
    <button type="button">Search</button>
  </div>
  <div class="gallery"></div>
  <div class='next'>Next Page</div>
</div>
Yousaf
  • 27,861
  • 6
  • 44
  • 69
Babilon
  • 21
  • 3
  • `document.getElementsByClassName` returns an array, so in your case, I think you can just use `document.getElementsByClassName("gallery")[0].appendChild(pic)` –  Sep 29 '21 at 07:58
  • yah it works but i don't understand why it start at 0 tho, can you explain? Thank you so much! – Babilon Sep 29 '21 at 08:39
  • The `getElementByClassName` method returns an array which is a collection of found elements. Right after the selector you are choosing the first found element by `[0]` index to which you append the pic. Let's say you had two galleries and you want to append the pic to the second gallery in the DOM, so you would select that gallery by index `[1]`. You cant't call the `appendChild` method on an array, you have to call it on a DOM element. –  Sep 29 '21 at 08:48

0 Answers0