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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0