0

I want to add an event to every image in the document, this is the code:

let images = document.getElementsByTagName("img")
const self = this;
for (var img of images) {
  img.onclick = function(e) {
      e.stopPropagation();
      if (!e.target.src) {
        return;
      }
      self.source = e.target.src;
      self.alt = e.target.alt;
  }
}

I log all of the images and find that only the last image has the click event. I had tried converting images into an array and used forEach methods, which got the same result. What's up? By the way, I do that in Vue's mounted hook method.

3
  • 1
    The code is totally fine. Commented Oct 12, 2017 at 8:56
  • It seems like all images have click events. Commented Oct 12, 2017 at 8:56
  • What is this here const self = this;? Commented Oct 12, 2017 at 8:57

1 Answer 1

1

Best way to attach events to multiple DOM elements is to use Event Delegation. You should attach the event to the parent element and check if the target element is img or not. Then you can access the src and alt attributes of the image.

var images = document.querySelector('.images');
images.onclick = function(e) {
  if(e.target.tagName === 'IMG') {
    console.log(e.target.src +" : " + e.target.alt);
  }
}
<div class="images">
  <img alt="1" src="https://randomuser.me/api/portraits/men/83.jpg" />
  <img alt="2" src="https://randomuser.me/api/portraits/med/men/83.jpg" />
  <img alt="3" src="https://randomuser.me/api/portraits/thumb/men/83.jpg" />
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

This is indeed the best way. I think it's worth noting that for matching non-empty HTML elements one should traverse the anchestor node tree of e.target until a match is found.
Yeah it is. But for my project using Event delegation here will be a bit sticky.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.