-2

so I know this question has been asked so many times but I still haven't found a solution to my problem:

HTML


<div class="thumbnails"></div>

JS

function createImg(index){
    tempImg.src = paths[index];
}

function appendImg(){
    var img = document.createElement('img');
    img.src = tempImg.src;

    createImg(index++);
    img.setAttribute('id', 'firsts');
    ** document.getElementsByClassName('thumbnails').appendChild(img); **
}

I want to append the newly created image/s to my div. I've tried many versions of doing it but nothing seemed to work.

If I use "document.body.appendChild(img);" this works just fine but it isn't what I need.

Andra
  • 61
  • 1
  • 9
  • 3
    `getElementsByClassName('thumbnails')` returns a collection. Index it. `getElementsByClassName('thumbnails')[0].appendChild(img)` (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) – Ryan Wilson Feb 24 '20 at 14:22
  • Besides reading the duplicated question, read documentation also helps a developer: [getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) – Calvin Nunes Feb 24 '20 at 14:22

1 Answers1

3

You can use document.querySelector() for this:

document.querySelector(".thumbnails").appendChild(img);

as querySelector() returns the first element within the document that matches the specified selector. But document.getElementsByClassName returns an array-like object of all child elements which have all of the given class names and this array-like object does not have any appendChild method.

palaѕн
  • 72,112
  • 17
  • 116
  • 136