0

I'm trying to add a eventlistener to a class but it's not working at all, I have done the same method with ID's and it worked perfectly but it's not working for classes. I'm still kinda new to Javascript so I apologize if it's something very simple.

const boxes = document.getElementsByClassName('box_img');

boxes.addEventListener("click", function(){    
    console.log('Hi');
    });
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
João Silva
  • 71
  • 2
  • 8
  • 2
    Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Dec 16 '21 at 13:46
  • Following @SebastianSimon [comment](https://stackoverflow.com/questions/70380069/add-eventlistener-to-a-class#comment124409728_70380069), see [`event.target.matches()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/matches) in the case that you are applying the listener to elements. – jsejcksn Dec 16 '21 at 13:51
  • @jsejcksn For clicks, `.closest` is usually a better option, i.e. `addEventListener("click", ({ target }) => { const boxImg = target.closest(".box_img"); if(boxImg){ console.log("Hi", boxImg); } });`. – Sebastian Simon Dec 16 '21 at 14:00
  • @SebastianSimon I suggested `matches` for validating that the event target **is** the one in the selector. Why do you think that `.closest` is "usually a better option for `click` handlers"? – jsejcksn Dec 16 '21 at 14:38
  • Clicking on the `` in `
    Hello, world!
    ` causes `event.target.matches(".box_img")` to return `false`. `closest` makes sure that the event target either is the one clicked or contains the element clicked. If this is not the desired behavior or if a different event type is used where this behavior would be counterintuitive, `.matches` can be used instead.
    – Sebastian Simon Dec 16 '21 at 14:43
  • @SebastianSimon Ah, of course: different cases. I agree with you there. – jsejcksn Dec 16 '21 at 16:08

0 Answers0