0

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>
John
  • 11
  • 1
  • 4
  • 2
    Does this answer your question? [querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript](https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid) – Emiel Zuurbier Sep 25 '20 at 14:26
  • Be more careful of what each function returns. The answer underneath the comments is correct and the link in the previous comment will help you. – Jabberwocky Sep 25 '20 at 14:29
  • while IDs are (supposed to be) unique, class names are not therefore `getElementById()` returns a single element (the only one that has that ID) while `getElementsByClassName` returns _a collection_ of elements (all the ones that have that class attribute) and, even if the collection contains a single element, you still have to access it using its index in the collection. Anyway, referring to your example, you should use ID and `getElementById()` as you want to identify a single element rather than groups of elements. – secan Sep 25 '20 at 14:34

2 Answers2

1

getElementById returns one element, but getElementsByClassName returns a collection. so what you can do is:

document.getElementsByClassName("test1")[0].src
document.getElementsByClassName("test2")[0].style.opacity
document.getElementsByClassName("test2")[0].style.visibility = "hidden";

And also getElementsById doesn't exist. it should be getElementById. Means without

Hasip Timurtas
  • 983
  • 2
  • 11
  • 20
0

getElementsByClassName return an array

You need to do

document.getElementsByClassName("test1")[0]
user2258152
  • 635
  • 5
  • 13