When you click the play button or the image, I want both images to go away.
I've targeted both of the elements in the nodelist, but when I click, only one of them goes away. The second one goes away only if I make a second click. I need them both to go away at the same time.
How do I click on either of two images to make them both go away?
const clickToPlay = document.querySelectorAll('.one, .two');
console.log("I see both objects: " Array.prototype.slice.call(clickToPlay));
clickToPlay.forEach((img) => {
img.addEventListener("click", function () {
this.remove();
});
});
.container {
position: relative;
}
img {
max-width: 100%;
height: auto;
}
.play {
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="container">
<img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b" class="one" alt="">
<div class="play two" alt=""></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can simply listen to the click
on the container
then remove the images:
const container = document.querySelectorAll(".container")[0];
container.addEventListener("click", function () {
const imgs = container.getElementsByTagName("img");
Array.from(imgs).forEach((img) => img.remove());
});
Example: https://codesandbox.io/s/smoosh-morning-jnx3k
CodePudding user response:
replace this.remove();
with
document.querySelectorAll('.one, .two').forEach((el) => { el.remove(); });
or if you prefer
clickToPlay.forEach((el) => { el.remove(); });