How do I iterate through a collection of elements? [duplicate]
This question is already answered here:
Set an attribute to an element when certain conditions are met
(1 answer)
Closed 11 months ago.
HTML:
<div class="info-block">
<img src="photo.jpg" alt="фотография" class="hidden">
<img src="photo2.jpg" alt="фотография" class="hidden">
<inframe width="789" height="444" src="https://www.youtube.com/watch?v=4QHFhIjF2L0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen class="hidden">
</div>
<div class="info-block">
<img src="photo.jpg" alt="фотография" class="hidden">
<img src="photo2.jpg" alt="фотография" class="hidden">
<inframe width="789" height="444" src="https://www.youtube.com/watch?v=4QHFhIjF2L0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen class="hidden">
</div>
CSS:
.hidden{
display: none;
}
JS:
function show(){
var button = document.querySelector('.info-block');
var img = document.querySelector('img');
var iframe = document.querySelector('iframe');
button.addEventListener('click', function(){
iframe.classList.toggle('hidden');
img.classList.toggle('hidden');
});
};
show();
The code should hide and show images and videos when clicked on <div class="display-block">
. It does this, but only for the first image and the first video in the first block. It doesn't work for the others.
After searching for information on this topic, I found out that button.addEventListener()
does not work for a collection of elements, and using a loop, you need to iterate through this collection and assign each element its own addEventListener. But I still didn't understand how to make such a cycle correctly. Please tell me
0
1 answers
function show(){
var buttons = document.querySelectorAll('.info-block');
buttons.forEach(el =>
el.addEventListener('click', function(){
this.querySelectorAll('img').forEach(img => img.classList.toggle('hidden'));
this.querySelector('iframe').classList.toggle('hidden');
});
);
}
function show(){
var buttons = document.querySelectorAll('.info-block');
buttons.forEach(btn =>
btn.addEventListener('click', function(){
this.querySelectorAll('*').forEach(el => el.classList.toggle('hidden'));
});
);
}
3
Author: Igor, 2020-03-23 20:09:18