Id property must be unique for each tag (in your case, each img
tag).
After naming each tag with an unique ID, you can get them with javascript with document.getElementById(id). Then you can use remove() to exclude these tags.
I made some modifications at your code. See if it is working.
<!DOCTYPE html>
<html>
<body>
<img
src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh"
id="first-img"
/>
<img
src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg"
id="second-img"
/>
<script text="javascript">
let firstImage = document.getElementById("first-img");
let secondImage = document.getElementById("second-img");
firstImage.addEventListener("click", () => {
firstImage.remove();
});
secondImage.addEventListener("click", () => {
secondImage.remove();
});
</script>
</body>
</html>
Though I’m not sure about what you’re going to do, I think you can do what you want by doing adding an event listener. Here is an example:
const image = document.querySelector("img");
const imgView = true;
function handleImgClick() {
if (imgView == true) {
image.style.display = "none";
imgView = false;
} else {
image.style.display = "inline-block";
imgView = true;
}
}
image.addEventListener("click",handleImgClick);
You can listen to all clicks in the body and remove the target it is a IMG tag.
document.addEventListener('click', function(e) {
if (e.target.tagName === 'IMG') {
e.target.remove();
}
});
img {
height: 60px;
}
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
<img src="https://picsum.photos/200/300">
Im trying to write a page that has images and when they are clicked they will disappear. I keep getting “.addEventListener is not a function”. What am I doing wrong/missing?
<!DOCTYPE html>
<html>
<body>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id = "img" />
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id = "img" />
<script text = "javascript">
let image_node = document.createElement('img');
img.addEventListener('click', () => {
img.parentNode.removeChild(img);
});
</script>
</body>
</html>
That is because you don’t have any variable called ‘img’ in your script. You should first get all the elements with tag ‘img'(