Search code examples
javascripthtmlimagebuttonsrc

Change the image src for multipe images


Here is my HTML:

<img class="image" src="" />
<img class="image" src="" />
<img class="image" src="" />
<button onclick="changeImages()">Change the images</button>

Here is my JavaScript:

function changeImages() {
document.getElementsByClassName("image").setAttribute("src", "images/image.png");
}

How can I make my code so that when I click the button, all those images change?

Thanks


Solution

  • getElementsByClassName() returns a collection of elements which doesn't have methods for applying attributes. You need to iterate through the collection and apply the attributes you want to each of its items. Something like:

    document.getElementsByClassName("image").forEach(function(image) {
        image.setAttribute("src", "images/image.png");
    });