Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda