For a site, I am using onclick
property in <img>
tag. The aim is when the image will be clicked some actions will be taken. For example, when image/1.jpg
will be clicked image/12.jpeg
will be disappeared. When I used id
with <img>
in HTML and used getElementsById
in JS it works properly. But when I used class
in <img>
tag in HTML and used getElementsByClassName
in JS it's not working.
<body>
<img class="test1" width="300" height="400" onclick="myFunction()" src="images/1.jpg">
<img class="test2" width="300" height="400" src="images/12.jpeg">
<script>
var img_array = ['images/1.jpg', 'images/12.jpeg'];
i = 0;
function myFunction() {
i++;
if (i == img_array.length - 1) {
document.getElementsByClassName("test1").src = img_array[i];
document.getElementsByClassName("test2").style.opacity = "0";
document.getElementsByClassName("test2").style.visibility = "hidden";
i = -1;
} else {
document.getElementsByClassName("test1").src = img_array[i];
document.getElementsByClassName("test2").style.opacity = "1";
document.getElementsByClassName("test2").style.visibility = "visible";
}
}
</script>
</body>