getElementsByClassName not working

have been trying to make appear an image using getElementsByClassName in javascript but really doesn’t work, where’s my mistake?

html :

<button class="openPic">Button to open picture</button>
<button class="closePic">Button to close picture</button>
<img src="slide.jpg" class="thePic">

css:

.thePic {
	display: none;
}

Javascript:

var openPic = document.getElementsByClassName("openPic");
let closePic = document.getElementsByClassName("closePic");

openPic.onclick = function() {
    thePic.style.display = 'block';
}
closePic.onclick = function() {
    thePic.style.display = 'none';
}

I actually discourage using IDs.

In this case just use:
document.querySelector('button.openPic');

Also-- avoid using .onclick() use addEventListener() instead.

1 Like