querySelectorAll for multiple classes not working

Hello im trying to show to different divs with some images on them at the same time using querySelectorAll but is just not working

<div id="id1" style="display:none;">
  <img src="1.jpg" alt="">
  <img src="2.jpg" alt="">
  <img src="3.jpg" alt="">
</div>
<div id="id2" style="display:none;">
  <img src="1.jpg" alt="">
  <img src="2.jpg" alt="">
  <img src="3.jpg" alt="">
</div>
img {
	visibility: hidden;
	clear: left;
	width: 30%;
}
button {
	float: left;
	margin: 5px;
}
  function show() {
  document.querySelectorAll ("#id1 #id2").style.display = "block";

}
function hide() {
  document.querySelectorAll ("#id1 #id2").style.display = "none";
}

querySelector and querySelectorAll both accept any valid CSS-type selector. So what you’re specifying is that you want to select all elements with an id of id2 that are children of an element with an id of id1 when you want to show, and vice versa when you want to hide.

Because it’s any CSS-type selector, you use commas to seperate: "firstSelector, secondSelector" (note it’s a single string, not multiple arguments)

Second issue is that querySelectorAll returns a collection of elements, not a single element, and you can’t set a style on a collection (you’re effectively trying to apply a style to an array). You would want to use forEach, like

document.querySelectorAll('.example').forEach(function(element) {
  element.style.display = 'none';
});

Edit also, really do use a common class like this :point_down:

1 Like

You can’t select them all like that.

add a class to each div.
<div id="id1" class="img_container" style="display:none;">

then use this instead:

const img_containers = document.querySelectorAll(".img_container");
img_containers.forEach((container) => container.style.display = "block");
1 Like

thanks alot now working, gonna take a look in the way you said for sure thanks alot

thanks alot very handy