Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda