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';
}
1 Like

The problem is getElementsByClassName does not return an element. Instead, it returns a NodeList. If you only have a single element with class=“openPic” then you would reference as:

var openPic = document.getElementsByClassName("openPic")[0]; // first element with class="openPic"

However, if you are only going to have one of these elements, I suggest giving it an id and use getElementById and then you will actually get an element.

Your code has another issue in that thePic is not defined anywhere in your JavaScript, so when you trying to reference in the onclick event handlers, it will error out.

1 Like

I actually discourage using IDs.

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

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

1 Like