In Javascript , I am trying to make event when click on img. i use addEventListener.
my code what do ? : there are six images in my page. and every image has two classes. the first class is 'img-class' and all the images have it.
and the second class is 'id' word and number. for example : the second class of image one is 'id1' , and the second class of image two is 'id2'.
what i want to do : i want when i click on any image from the six image the console print the second id of the image which i clicked.
the problem is 'no thing happen when i click on the image , no print error in the console no thing happen' .
i tried to get the second class without click event and work.
so the problem in event function.
where is the problem ?
this is javascript code :
var Img_Img = document.querySelectorAll('.img-class');
Img_Img.forEach(Img_Img_Img => {
Img_Img_Img.addEventListener("click" , ()=>{
if (Img_Img_Img.classList.contains("imgimg") != null) {
Img_Img_Img.classList.remove("imgimg");
}
if (Img_Img_Img.classList.contains("imgimg") == null) {
Img_Img_Img.classList.add("imgimg");
}
document.querySelectorAll('.imgimg').forEach( imgimgimg => {
var idid = imgimgimg.getAttribute('class').split(' ')[1];
console.log(idid);
});
});
});
html code :
<div class = "images-images">
<div>
<img src = "Images/watch.jpg" class = "img-class id1">
<div class = "overlay-image-image"></div>
</div>
<div>
<img src = "Images/watch_2.jpg" class = "img-class id2">
<div class = "overlay-image-image"></div>
</div>
<div>
<img src = "Images/card.jpg" class = "img-class id3">
<div class = "overlay-image-image"></div>
</div>
<div>
<img src = "Images/shoes.jpg" class = "img-class id4">
<div class = "overlay-image-image"></div>
</div>
<div>
<img src = "Images/card_2.jpg" class = "img-class id5">
<div class = "overlay-image-image"></div>
</div>
<div>
<img src = "Images/headphones.jpg" class = "img-class id6">
<div class = "overlay-image-image"></div>
</div>
</div>
CodePudding user response:
Img_Img_Img.classList.contains() method always return boolean value. So your code should be follows.
if (Img_Img_Img.classList.contains("imgimg") == false) {
Img_Img_Img.classList.add("imgimg");
}
CodePudding user response:
You can use the substring method to get only part of a string.
const images = document.querySelectorAll('.img-class');
images.forEach(function (image) {image.addEventListener('click', () => console.log(image.className.substring(10, 13)))})
<div class = "images-images">
<div>
<img src = "Images/watch.jpg" class = "img-class id1">
<div class = "overlay-image-image"></div>
<div>
<img src = "Images/watch_2.jpg" class = "img-class id2">
<div class = "overlay-image-image"></div>
</div>
</div>