There are some photos in the gl block. How do I get src photos that I click on?

Here is an example (simplified, because without a solution with img, it makes no sense to write further than it):

<div id="pic"> <img src="img/img-1.jpg" alt=""> <img src="img/img-2.jpg" alt=""> <img src="img/img-3.jpg" alt=""> <img src="img/img-4.jpg" alt=""> <img src="img/img-5.jpg" alt=""> </div> 

By pressing any of these images performs the same function (opening a photo in a modal window). I'm having difficulty getting the src of the photo I clicked on. I'm trying to get all the photos in the block using:

 pic.getElementsByTagName('img') 

, and then get getAttribute(src)

But it does not work. It turns out to get a src photo if I specify:

 pic.getElementsByTagName('img')[0] 

and above ([1] [2], etc.). Then everything works well for me.

As you understand, in the case above, I will take src only for that img which I will indicate [the number], and I need to catch by what img the click was made.

PS please, without ready codes. Only hints how to do it.

  • depends on where and how you get them, if <img onclick="hey(this);"/> then function hey(x){ console.log(x.src); } function hey(x){ console.log(x.src); } - teran
  • I will not write onclick () in each line, it is not beautiful) I'm trying to catch on what img was a click and pick up src. The variant is below working, but I'm still trying to catch it with my head - Disciple
  • Duck, I tell you, and it depends on how you do it in general, you hang up the click handler on the pictures. - teran
  • If it is not difficult for you, please see my code jsfiddle.net/g49dq5hn/1 . I added comments everywhere. Everything works, but I can't understand: is it possible to just hang myimg.onclick = function instead of a handler {} {} can I write my code by reference to another? For any help, a low bow - Disciple

1 answer 1

 [...document.querySelectorAll("div > img")].forEach(item => { item.addEventListener("click", (e) => { console.log(e.currentTarget.getAttribute("src")); }); }); 
 .fix-snippet>div { height: 100px; width: 100px; display: inline-block; } img { width: 100%; height: 100%; cursor: pointer; } 
 <div class="fix-snippet"> <div> <img src="https://picsum.photos/g/200/301" alt="1"> </div> <div> <img src="https://picsum.photos/g/200/302" alt="2"> </div> <div> <img src="https://picsum.photos/g/200/303" alt="3"> </div> <div> <img src="https://picsum.photos/g/200/304" alt="4"> </div> <div> <img src="https://picsum.photos/g/200/305" alt="5"> </div> </div> 

  • You should not specify styles for a div in a snippet, otherwise its console also starts using the same styles) - CbIPoK2513 February
  • @ CbIPoK2513, heh, did not know :) - meine