Why does the if statement not work with the getElementById?

0

What I try to do is that every time I click on the button it shows me the following image. However, it does not work. In some websites they say it does not work because the route (img.jpg) is not correct as a condition, but I do not understand why. Thanks!

function showImage(){
	

	if (document.getElementById('imgLabel1').src == 'img1.jpg')
	{
		document.getElementById('imgLabel1').src  = 'img2.jpg';
	}
	else if (document.getElementById('imgLabel1').src == 'img2.jpg')
	{
		document.getElementById('imgLabel1').src  = 'img3.jpg';
	}
	else
	{
		document.getElementById('imgLabel1').src  = 'img1.jpg';
	}

}
<!DOCTYPE html>
<html lang="es">
<head>
	<meta charset="UTF-8">
	<script type="text/javascript" src="gallery.js"></script>
	<link rel="stylesheet" href="styleImg.css">
	<title></title>
</head>
<body>
	<img id="imgLabel1" src="img1.jpg">
	<button id="next" onclick="showImage()">NEXT IMAGE</button>
</body>
</html>
    
asked by jaranza 30.12.2017 в 02:15
source

2 answers

1

The problem is the condition, the path of the image to be loaded by the DOM is from the root of your domain and its directory until you get to the image.

  

Example: www.google.es/img1.jpg

A possible solution is to check the last segment of the url of the image, which is the one that interests you and make your function work.

function showImage() {
	const img = document.getElementById('imgLabel1');
	const source = img.src.substr(img.src.lastIndexOf('/') + 1);
	const sources = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
	const index = sources.findIndex(src => src === source) + 1;
	img.src = sources[index] || sources[0];
}
<img id="imgLabel1" src="img1.jpg">
<button id="next" onclick="showImage()">NEXT IMAGE</button>
    
answered by 30.12.2017 / 02:33
source
0

The error is that by doing only img.png , the full url of the image will be obtained from the current domain, you can see it here:

window.addEventListener("load", () => {
  var img = document.createElement("IMG");
      img.src = "img.png";
      
  console.info(img.src);
});

What you simply must do is add the complete url

    
answered by 30.12.2017 в 21:00