Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
Creating new div in existing one

I can't figure out what I'm doing wrong.

This code works fine:

   pic.forEach(photo => {
        
    const newDiv = document.createElement("div");
    newDiv.className = 'photo';
    newDiv.innerHTML = `<img src=${photo.urls.small}>`
    document.body.appendChild(newDiv); 

but I want to nest this newDiv inside exisitng one, so I prepared DIV with class photos.

const pic = result.results;
    pic.forEach(photo => {
    const gallery = document.getElementsByClassName('photos');  
    const newDiv = document.createElement("div");
    newDiv.className = 'photo';
    newDiv.innerHTML = `<img src=${photo.urls.small}>`
    gallery.appendChild(newDiv);

and this one it's not working.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The function getElementsByClassName will return an Array, an HTMLCollectionOf<Element>, that is why, calling directly appendChild won't work, you have some options in this case. Loop through all Elements, but it seems to be only one.

 const gallery = document.getElementsByClassName('photos')[0];  
 // Both will get only the first Element that matches
 const gallery = document.querySelector('.photos');  

Now you can append the new Element.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!