change the value of the src attribute of all the image

in html i am changing img tag src with javascript. but it only change the first one i need to change all the img src . How can i change it?

html

<img src="compman01.gif" width="107" height="98">
<img src="compman02.gif" width="107" height="98">
<img src="compman03.gif" width="107" height="98">
<img src="compman04.gif" width="107" height="98">
<img src="compman05.gif" width="107" height="98">

javascript

document.getElementsByTagName("img")[0].src = "hackanm.gif";

Upvotes: 1

Views: 666

Answers (3)

Zeeshan Ahmad
Zeeshan Ahmad

Reputation: 5644

document.querySelectorAll('img').forEach((img) => {
  img.setAttribute('src', "hackanm.gif");
})

Upvotes: 3

Vaisakh Pradeep
Vaisakh Pradeep

Reputation: 141

document.getElementsByTagName("img") will return an array like object which you can loop through.

let images = document.getElementsByTagName("img");
for(let i = 0; i < images.length; i++) {
    images[i].src = "hackanm.gif";
}

Upvotes: 1

HAK
HAK

Reputation: 458

document.getElementsByTagName("img").forEach((imgElement) =>{
  imgElement.src = "hackanm.gif";
  
}); 

Upvotes: 0

Related Questions