DEV Community

Paul
Paul

Posted on

How can I check if an image in a local folder exists with plain JavaScript?

Basically my question is how can I do this? Anywhere I looked I couldn't find answers.

for(var i = 0; i < 4; i++){
var img = document.createElement("img");
img.style.src = img/${i}.png;

if(img exists)
     document.body.appendChild(img);
Enter fullscreen mode Exit fullscreen mode

}
Also is this possible somehow?
for( i = 0; i < how many images are inside folder; i++)

Top comments (4)

Collapse
 
oculus42 profile image
Samuel Rouse

You can add onload and onerror event handlers to the img element you created. onload can be used to add the image to the page, but the order would depend on the order the requests complete, so they may appear out of sequence.

You could place them all on the page after setting img.style.display = 'none'; and use the event handlers to remove the style in onload or remove the element with onerror.

There are a couple of other ways you could go about this, but that is probably the simplest way to get started.

Collapse
 
pauladrian profile image
Paul

for(var i = 0; i < 4; i++){

var img = new Image();
img.addEventListener(onerror, console.log('asd'));

img.src = `img/${i}.png`;
document.body.appendChild(img);
Enter fullscreen mode Exit fullscreen mode

}

in my folder i have 1.png 2.png 3.png but not 0.png and yet this code gives me 4 times asd, what am i doing wrong?

Collapse
 
oculus42 profile image
Samuel Rouse

You are starting your loop with zero as the base value for i. The increment in the afterthought runs after each loop. If you don't want to include zero, you should start with 1.

 for (let i = 1; I < 4; i += 1) {
  // this will generate 1,2,3
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wraith profile image
Jake Lundberg

First guess would be to confirm that your src path is correct.