0

I am trying to make the elements with the same class have the same function.

to test if it worked i tried to alert("test") when one of the elements are clicked. But this does not seem to work.

Does anyone have a solution?

var expand = document.getElementsByClassName("expand");

expand.addEventListener("click", function(){
    alert("test");
})
  • `getElementsByClassName` returns an array-like object. You want to add even listeners to the *items* of that "array", not to the "array" itself. – Orius Feb 16 '22 at 07:52
  • I recommend you to iterate `expand` in order to add event listeners to all elements. – Deividgp Feb 16 '22 at 07:53
  • Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of a loop — it’s more maintainable and applies to dynamically added elements. See [the tag info](/tags/event-delegation/info) and [this Q&A](/q/1687296/4642212). Use the [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback): `theRoot.addEventListener("click", ({` [`target`](//developer.mozilla.org/docs/Web/API/Event/target) `}) => { const exp = target.closest(".expand"); if(exp){ exp.classList.toggle("expand"); } });`. – Sebastian Simon Feb 16 '22 at 07:56

0 Answers0