Home > Back-end >  if an "url image" is equal to an image got by document.getElementsByTagName("img"
if an "url image" is equal to an image got by document.getElementsByTagName("img"

Time:12-08

I am trying to get all images and check if one of these images is equal to an image (specified by me) change it to another image (specified by me). Thanks!

var object = document.getElementsByTagName("img");
//object[0].src is = to "image/image1.png";
if(object[0].src == "image/image1.png")   {
    object[0].src = "image/image2.png"
}   

CodePudding user response:

You can use a for loop to check each image:

var images = [...document.getElementsByTagName("img")]

for (const image of images) {
    if (image.src === "image/image1.png") {
        // do something
        image.src = "somethingelse.png"
    }
}

[...] converts the HTMLCollection document.getElementsByTagName returns so you can iterate over it.

CodePudding user response:

I found the solutions by debugging!.

so i was trying to check if an image is equal to an image of the all images i got (specifing one of them for example the first image so object[0]) in var object by document.getElementsByTagName("src)

with this if: if(object[0].src == "image/image1.png) this return always false because object[0].src return file:///C:/Users/Name/Documents/foldername/image/image1.png" so checking if this is equal to "image/image1.png" return always false. and the solution is:

if(object[0].src == file:///C:/Users/Name/Documents/foldername/image/image1.png"){ 
         //do something
    }

to know the complete url: alert(object[0].src);

sorry for my bad English!

  • Related