Home > Software design >  Creating new div in existing one
Creating new div in existing one

Time:11-03

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.

CodePudding user response:

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.

  • Related